Bug 18936: (follow-up) Add foreign key and scope enhancement to circ rules
[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         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
918
919         my $ten_days_before = dt_from_string->add( days => -10 );
920         my $ten_days_ahead = dt_from_string->add( days => 10 );
921
922         # Patron is expired and BlockExpiredPatronOpacActions=0
923         # => auto renew is allowed
924         t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
925         my $patron = $expired_borrower;
926         my $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
927         ( $renewokay, $error ) =
928           CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
929         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
930         is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
931         Koha::Checkouts->find( $checkout->issue_id )->delete;
932
933
934         # Patron is expired and BlockExpiredPatronOpacActions=1
935         # => auto renew is not allowed
936         t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
937         $patron = $expired_borrower;
938         $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
939         ( $renewokay, $error ) =
940           CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
941         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
942         is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
943         Koha::Checkouts->find( $checkout->issue_id )->delete;
944
945
946         # Patron is not expired and BlockExpiredPatronOpacActions=1
947         # => auto renew is allowed
948         t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
949         $patron = $renewing_borrower;
950         $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
951         ( $renewokay, $error ) =
952           CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
953         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
954         is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
955         Koha::Checkouts->find( $checkout->issue_id )->delete;
956     };
957
958     subtest "GetLatestAutoRenewDate" => sub {
959         plan tests => 5;
960         my $item_to_auto_renew = $builder->build(
961             {   source => 'Item',
962                 value  => {
963                     biblionumber  => $biblio->biblionumber,
964                     homebranch    => $branch,
965                     holdingbranch => $branch,
966                 }
967             }
968         );
969
970         my $ten_days_before = dt_from_string->add( days => -10 );
971         my $ten_days_ahead  = dt_from_string->add( days => 10 );
972         AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
973         Koha::CirculationRules->set_rules(
974             {
975                 categorycode => undef,
976                 branchcode   => undef,
977                 itemtype     => undef,
978                 rules        => {
979                     norenewalbefore       => '7',
980                     no_auto_renewal_after => '',
981                     no_auto_renewal_after_hard_limit => undef,
982                 }
983             }
984         );
985         my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
986         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' );
987         my $five_days_before = dt_from_string->add( days => -5 );
988         Koha::CirculationRules->set_rules(
989             {
990                 categorycode => undef,
991                 branchcode   => undef,
992                 itemtype     => undef,
993                 rules        => {
994                     norenewalbefore       => '10',
995                     no_auto_renewal_after => '5',
996                     no_auto_renewal_after_hard_limit => undef,
997                 }
998             }
999         );
1000         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1001         is( $latest_auto_renew_date->truncate( to => 'minute' ),
1002             $five_days_before->truncate( to => 'minute' ),
1003             'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
1004         );
1005         my $five_days_ahead = dt_from_string->add( days => 5 );
1006         $dbh->do(q{UPDATE circulation_rules SET rule_value = '10' WHERE rule_name = 'norenewalbefore'});
1007         $dbh->do(q{UPDATE circulation_rules SET rule_value = '15' WHERE rule_name = 'no_auto_renewal_after'});
1008         $dbh->do(q{UPDATE circulation_rules SET rule_value = NULL WHERE rule_name = 'no_auto_renewal_after_hard_limit'});
1009         Koha::CirculationRules->set_rules(
1010             {
1011                 categorycode => undef,
1012                 branchcode   => undef,
1013                 itemtype     => undef,
1014                 rules        => {
1015                     norenewalbefore       => '10',
1016                     no_auto_renewal_after => '15',
1017                     no_auto_renewal_after_hard_limit => undef,
1018                 }
1019             }
1020         );
1021         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1022         is( $latest_auto_renew_date->truncate( to => 'minute' ),
1023             $five_days_ahead->truncate( to => 'minute' ),
1024             'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
1025         );
1026         my $two_days_ahead = dt_from_string->add( days => 2 );
1027         Koha::CirculationRules->set_rules(
1028             {
1029                 categorycode => undef,
1030                 branchcode   => undef,
1031                 itemtype     => undef,
1032                 rules        => {
1033                     norenewalbefore       => '10',
1034                     no_auto_renewal_after => '',
1035                     no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1036                 }
1037             }
1038         );
1039         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1040         is( $latest_auto_renew_date->truncate( to => 'day' ),
1041             $two_days_ahead->truncate( to => 'day' ),
1042             'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
1043         );
1044         Koha::CirculationRules->set_rules(
1045             {
1046                 categorycode => undef,
1047                 branchcode   => undef,
1048                 itemtype     => undef,
1049                 rules        => {
1050                     norenewalbefore       => '10',
1051                     no_auto_renewal_after => '15',
1052                     no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1053                 }
1054             }
1055         );
1056         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1057         is( $latest_auto_renew_date->truncate( to => 'day' ),
1058             $two_days_ahead->truncate( to => 'day' ),
1059             'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
1060         );
1061
1062     };
1063     # Too many renewals
1064
1065     # set policy to forbid renewals
1066     Koha::CirculationRules->set_rules(
1067         {
1068             categorycode => undef,
1069             branchcode   => undef,
1070             itemtype     => undef,
1071             rules        => {
1072                 norenewalbefore => undef,
1073                 renewalsallowed => 0,
1074             }
1075         }
1076     );
1077
1078     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
1079     is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
1080     is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
1081
1082     # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
1083     t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
1084     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1085
1086     C4::Overdues::UpdateFine(
1087         {
1088             issue_id       => $issue->id(),
1089             itemnumber     => $item_1->itemnumber,
1090             borrowernumber => $renewing_borrower->{borrowernumber},
1091             amount         => 15.00,
1092             type           => q{},
1093             due            => Koha::DateUtils::output_pref($datedue)
1094         }
1095     );
1096
1097     my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower->{borrowernumber} })->next();
1098     is( $line->debit_type_code, 'OVERDUE', 'Account line type is OVERDUE' );
1099     is( $line->status, 'UNRETURNED', 'Account line status is UNRETURNED' );
1100     is( $line->amountoutstanding+0, 15, 'Account line amount outstanding is 15.00' );
1101     is( $line->amount+0, 15, 'Account line amount is 15.00' );
1102     is( $line->issue_id, $issue->id, 'Account line issue id matches' );
1103
1104     my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
1105     is( $offset->type, 'OVERDUE', 'Account offset type is Fine' );
1106     is( $offset->amount+0, 15, 'Account offset amount is 15.00' );
1107
1108     t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
1109     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
1110
1111     LostItem( $item_1->itemnumber, 'test', 1 );
1112
1113     $line = Koha::Account::Lines->find($line->id);
1114     is( $line->debit_type_code, 'OVERDUE', 'Account type remains as OVERDUE' );
1115     isnt( $line->status, 'UNRETURNED', 'Account status correctly changed from UNRETURNED to RETURNED' );
1116
1117     my $item = Koha::Items->find($item_1->itemnumber);
1118     ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
1119     my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
1120     is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
1121
1122     my $total_due = $dbh->selectrow_array(
1123         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1124         undef, $renewing_borrower->{borrowernumber}
1125     );
1126
1127     is( $total_due+0, 15, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
1128
1129     C4::Context->dbh->do("DELETE FROM accountlines");
1130
1131     C4::Overdues::UpdateFine(
1132         {
1133             issue_id       => $issue2->id(),
1134             itemnumber     => $item_2->itemnumber,
1135             borrowernumber => $renewing_borrower->{borrowernumber},
1136             amount         => 15.00,
1137             type           => q{},
1138             due            => Koha::DateUtils::output_pref($datedue)
1139         }
1140     );
1141
1142     LostItem( $item_2->itemnumber, 'test', 0 );
1143
1144     my $item2 = Koha::Items->find($item_2->itemnumber);
1145     ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
1146     ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
1147
1148     $total_due = $dbh->selectrow_array(
1149         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1150         undef, $renewing_borrower->{borrowernumber}
1151     );
1152
1153     ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
1154
1155     my $future = dt_from_string();
1156     $future->add( days => 7 );
1157     my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
1158     ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
1159
1160     # Users cannot renew any item if there is an overdue item
1161     t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
1162     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
1163     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
1164     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
1165     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
1166
1167     my $manager = $builder->build_object({ class => "Koha::Patrons" });
1168     t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
1169     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1170     $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
1171     LostItem( $item_3->itemnumber, 'test', 0 );
1172     my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
1173     is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
1174     is(
1175         $accountline->description,
1176         sprintf( "%s %s %s",
1177             $item_3->biblio->title  || '',
1178             $item_3->barcode        || '',
1179             $item_3->itemcallnumber || '' ),
1180         "Account line description must not contain 'Lost Items ', but be title, barcode, itemcallnumber"
1181     );
1182 };
1183
1184 subtest "GetUpcomingDueIssues" => sub {
1185     plan tests => 12;
1186
1187     my $branch   = $library2->{branchcode};
1188
1189     #Create another record
1190     my $biblio2 = $builder->build_sample_biblio();
1191
1192     #Create third item
1193     my $item_1 = Koha::Items->find($reused_itemnumber_1);
1194     my $item_2 = Koha::Items->find($reused_itemnumber_2);
1195     my $item_3 = $builder->build_sample_item(
1196         {
1197             biblionumber     => $biblio2->biblionumber,
1198             library          => $branch,
1199             itype            => $itemtype,
1200         }
1201     );
1202
1203
1204     # Create a borrower
1205     my %a_borrower_data = (
1206         firstname =>  'Fridolyn',
1207         surname => 'SOMERS',
1208         categorycode => $patron_category->{categorycode},
1209         branchcode => $branch,
1210     );
1211
1212     my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1213     my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
1214
1215     my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
1216     my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
1217     my $today = DateTime->today(time_zone => C4::Context->tz());
1218
1219     my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
1220     my $datedue = dt_from_string( $issue->date_due() );
1221     my $issue2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
1222     my $datedue2 = dt_from_string( $issue->date_due() );
1223
1224     my $upcoming_dues;
1225
1226     # GetUpcomingDueIssues tests
1227     for my $i(0..1) {
1228         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1229         is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
1230     }
1231
1232     #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
1233     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1234     is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
1235
1236     for my $i(3..5) {
1237         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1238         is ( scalar( @$upcoming_dues ), 1,
1239             "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
1240     }
1241
1242     # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
1243
1244     my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
1245
1246     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
1247     is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
1248
1249     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
1250     is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
1251
1252     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
1253     is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
1254
1255     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 }  );
1256     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1257
1258     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1259     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1260
1261     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1262     is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1263
1264 };
1265
1266 subtest "Bug 13841 - Do not create new 0 amount fines" => sub {
1267     my $branch   = $library2->{branchcode};
1268
1269     my $biblio = $builder->build_sample_biblio();
1270
1271     #Create third item
1272     my $item = $builder->build_sample_item(
1273         {
1274             biblionumber     => $biblio->biblionumber,
1275             library          => $branch,
1276             itype            => $itemtype,
1277         }
1278     );
1279
1280     # Create a borrower
1281     my %a_borrower_data = (
1282         firstname =>  'Kyle',
1283         surname => 'Hall',
1284         categorycode => $patron_category->{categorycode},
1285         branchcode => $branch,
1286     );
1287
1288     my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1289
1290     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1291     my $issue = AddIssue( $borrower, $item->barcode );
1292     UpdateFine(
1293         {
1294             issue_id       => $issue->id(),
1295             itemnumber     => $item->itemnumber,
1296             borrowernumber => $borrowernumber,
1297             amount         => 0,
1298             type           => q{}
1299         }
1300     );
1301
1302     my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1303     my $count = $hr->{count};
1304
1305     is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1306 };
1307
1308 subtest "AllowRenewalIfOtherItemsAvailable tests" => sub {
1309     $dbh->do('DELETE FROM issues');
1310     $dbh->do('DELETE FROM items');
1311     $dbh->do('DELETE FROM circulation_rules');
1312     Koha::CirculationRules->set_rules(
1313         {
1314             categorycode => undef,
1315             itemtype     => undef,
1316             branchcode   => undef,
1317             rules        => {
1318                 reservesallowed => 25,
1319                 issuelength     => 14,
1320                 lengthunit      => 'days',
1321                 renewalsallowed => 1,
1322                 renewalperiod   => 7,
1323                 norenewalbefore => undef,
1324                 auto_renew      => 0,
1325                 fine            => .10,
1326                 chargeperiod    => 1,
1327                 maxissueqty     => 20
1328             }
1329         }
1330     );
1331     my $biblio = $builder->build_sample_biblio();
1332
1333     my $item_1 = $builder->build_sample_item(
1334         {
1335             biblionumber     => $biblio->biblionumber,
1336             library          => $library2->{branchcode},
1337             itype            => $itemtype,
1338         }
1339     );
1340
1341     my $item_2= $builder->build_sample_item(
1342         {
1343             biblionumber     => $biblio->biblionumber,
1344             library          => $library2->{branchcode},
1345             itype            => $itemtype,
1346         }
1347     );
1348
1349     my $borrowernumber1 = Koha::Patron->new({
1350         firstname    => 'Kyle',
1351         surname      => 'Hall',
1352         categorycode => $patron_category->{categorycode},
1353         branchcode   => $library2->{branchcode},
1354     })->store->borrowernumber;
1355     my $borrowernumber2 = Koha::Patron->new({
1356         firstname    => 'Chelsea',
1357         surname      => 'Hall',
1358         categorycode => $patron_category->{categorycode},
1359         branchcode   => $library2->{branchcode},
1360     })->store->borrowernumber;
1361
1362     my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1363     my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1364
1365     my $issue = AddIssue( $borrower1, $item_1->barcode );
1366
1367     my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1368     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1369
1370     AddReserve(
1371         $library2->{branchcode}, $borrowernumber2, $biblio->biblionumber,
1372         '',  1, undef, undef, '',
1373         undef, undef, undef
1374     );
1375
1376     Koha::CirculationRules->set_rules(
1377         {
1378             categorycode => undef,
1379             itemtype     => undef,
1380             branchcode   => undef,
1381             rules        => {
1382                 onshelfholds => 0,
1383             }
1384         }
1385     );
1386     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1387     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1388     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1389
1390     Koha::CirculationRules->set_rules(
1391         {
1392             categorycode => undef,
1393             itemtype     => undef,
1394             branchcode   => undef,
1395             rules        => {
1396                 onshelfholds => 0,
1397             }
1398         }
1399     );
1400     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1401     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1402     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1403
1404     Koha::CirculationRules->set_rules(
1405         {
1406             categorycode => undef,
1407             itemtype     => undef,
1408             branchcode   => undef,
1409             rules        => {
1410                 onshelfholds => 1,
1411             }
1412         }
1413     );
1414     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1415     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1416     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1417
1418     Koha::CirculationRules->set_rules(
1419         {
1420             categorycode => undef,
1421             itemtype     => undef,
1422             branchcode   => undef,
1423             rules        => {
1424                 onshelfholds => 1,
1425             }
1426         }
1427     );
1428     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1429     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1430     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1431
1432     # Setting item not checked out to be not for loan but holdable
1433     ModItem({ notforloan => -1 }, $biblio->biblionumber, $item_2->itemnumber);
1434
1435     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1436     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' );
1437 };
1438
1439 {
1440     # Don't allow renewing onsite checkout
1441     my $branch   = $library->{branchcode};
1442
1443     #Create another record
1444     my $biblio = $builder->build_sample_biblio();
1445
1446     my $item = $builder->build_sample_item(
1447         {
1448             biblionumber     => $biblio->biblionumber,
1449             library          => $branch,
1450             itype            => $itemtype,
1451         }
1452     );
1453
1454     my $borrowernumber = Koha::Patron->new({
1455         firstname =>  'fn',
1456         surname => 'dn',
1457         categorycode => $patron_category->{categorycode},
1458         branchcode => $branch,
1459     })->store->borrowernumber;
1460
1461     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1462
1463     my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1464     my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $item->itemnumber );
1465     is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1466     is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1467 }
1468
1469 {
1470     my $library = $builder->build({ source => 'Branch' });
1471
1472     my $biblio = $builder->build_sample_biblio();
1473
1474     my $item = $builder->build_sample_item(
1475         {
1476             biblionumber     => $biblio->biblionumber,
1477             library          => $library->{branchcode},
1478             itype            => $itemtype,
1479         }
1480     );
1481
1482     my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1483
1484     my $issue = AddIssue( $patron, $item->barcode );
1485     UpdateFine(
1486         {
1487             issue_id       => $issue->id(),
1488             itemnumber     => $item->itemnumber,
1489             borrowernumber => $patron->{borrowernumber},
1490             amount         => 1,
1491             type           => q{}
1492         }
1493     );
1494     UpdateFine(
1495         {
1496             issue_id       => $issue->id(),
1497             itemnumber     => $item->itemnumber,
1498             borrowernumber => $patron->{borrowernumber},
1499             amount         => 2,
1500             type           => q{}
1501         }
1502     );
1503     is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1504 }
1505
1506 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1507     plan tests => 24;
1508
1509     my $homebranch    = $builder->build( { source => 'Branch' } );
1510     my $holdingbranch = $builder->build( { source => 'Branch' } );
1511     my $otherbranch   = $builder->build( { source => 'Branch' } );
1512     my $patron_1      = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1513     my $patron_2      = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1514
1515     my $item = $builder->build_sample_item(
1516         {
1517             homebranch    => $homebranch->{branchcode},
1518             holdingbranch => $holdingbranch->{branchcode},
1519         }
1520     )->unblessed;
1521
1522     set_userenv($holdingbranch);
1523
1524     my $issue = AddIssue( $patron_1->unblessed, $item->{barcode} );
1525     is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
1526
1527     my ( $error, $question, $alerts );
1528
1529     # AllowReturnToBranch == anywhere
1530     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1531     ## Test that unknown barcodes don't generate internal server errors
1532     set_userenv($homebranch);
1533     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1534     ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1535     ## Can be issued from homebranch
1536     set_userenv($homebranch);
1537     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1538     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1539     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1540     ## Can be issued from holdingbranch
1541     set_userenv($holdingbranch);
1542     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1543     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1544     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1545     ## Can be issued from another branch
1546     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1547     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1548     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1549
1550     # AllowReturnToBranch == holdingbranch
1551     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1552     ## Cannot be issued from homebranch
1553     set_userenv($homebranch);
1554     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1555     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1556     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1557     is( $error->{branch_to_return},         $holdingbranch->{branchcode}, 'branch_to_return matched holdingbranch' );
1558     ## Can be issued from holdinbranch
1559     set_userenv($holdingbranch);
1560     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1561     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1562     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1563     ## Cannot be issued from another branch
1564     set_userenv($otherbranch);
1565     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1566     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1567     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1568     is( $error->{branch_to_return},         $holdingbranch->{branchcode}, 'branch_to_return matches holdingbranch' );
1569
1570     # AllowReturnToBranch == homebranch
1571     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1572     ## Can be issued from holdinbranch
1573     set_userenv($homebranch);
1574     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1575     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1576     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1577     ## Cannot be issued from holdinbranch
1578     set_userenv($holdingbranch);
1579     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1580     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1581     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1582     is( $error->{branch_to_return},         $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1583     ## Cannot be issued from holdinbranch
1584     set_userenv($otherbranch);
1585     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1586     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1587     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1588     is( $error->{branch_to_return},         $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1589
1590     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1591 };
1592
1593 subtest 'AddIssue & AllowReturnToBranch' => sub {
1594     plan tests => 9;
1595
1596     my $homebranch    = $builder->build( { source => 'Branch' } );
1597     my $holdingbranch = $builder->build( { source => 'Branch' } );
1598     my $otherbranch   = $builder->build( { source => 'Branch' } );
1599     my $patron_1      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1600     my $patron_2      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1601
1602     my $item = $builder->build_sample_item(
1603         {
1604             homebranch    => $homebranch->{branchcode},
1605             holdingbranch => $holdingbranch->{branchcode},
1606         }
1607     )->unblessed;
1608
1609     set_userenv($holdingbranch);
1610
1611     my $ref_issue = 'Koha::Checkout';
1612     my $issue = AddIssue( $patron_1, $item->{barcode} );
1613
1614     my ( $error, $question, $alerts );
1615
1616     # AllowReturnToBranch == homebranch
1617     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1618     ## Can be issued from homebranch
1619     set_userenv($homebranch);
1620     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from homebranch');
1621     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1622     ## Can be issued from holdinbranch
1623     set_userenv($holdingbranch);
1624     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from holdingbranch');
1625     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1626     ## Can be issued from another branch
1627     set_userenv($otherbranch);
1628     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from otherbranch');
1629     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1630
1631     # AllowReturnToBranch == holdinbranch
1632     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1633     ## Cannot be issued from homebranch
1634     set_userenv($homebranch);
1635     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from homebranch');
1636     ## Can be issued from holdingbranch
1637     set_userenv($holdingbranch);
1638     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - holdingbranch | Can be issued from holdingbranch');
1639     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1640     ## Cannot be issued from another branch
1641     set_userenv($otherbranch);
1642     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from otherbranch');
1643
1644     # AllowReturnToBranch == homebranch
1645     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1646     ## Can be issued from homebranch
1647     set_userenv($homebranch);
1648     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - homebranch | Can be issued from homebranch' );
1649     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1650     ## Cannot be issued from holdinbranch
1651     set_userenv($holdingbranch);
1652     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from holdingbranch' );
1653     ## Cannot be issued from another branch
1654     set_userenv($otherbranch);
1655     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from otherbranch' );
1656     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1657 };
1658
1659 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1660     plan tests => 8;
1661
1662     my $library = $builder->build( { source => 'Branch' } );
1663     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1664     my $item_1 = $builder->build_sample_item(
1665         {
1666             library => $library->{branchcode},
1667         }
1668     )->unblessed;
1669     my $item_2 = $builder->build_sample_item(
1670         {
1671             library => $library->{branchcode},
1672         }
1673     )->unblessed;
1674
1675     my ( $error, $question, $alerts );
1676
1677     # Patron cannot issue item_1, they have overdues
1678     my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1679     my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, $yesterday );    # Add an overdue
1680
1681     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1682     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1683     is( keys(%$error) + keys(%$alerts),  0, 'No key for error and alert' . str($error, $question, $alerts) );
1684     is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
1685
1686     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1687     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1688     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1689     is( $error->{USERBLOCKEDOVERDUE},      1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
1690
1691     # Patron cannot issue item_1, they are debarred
1692     my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1693     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
1694     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1695     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1696     is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
1697
1698     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
1699     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1700     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1701     is( $error->{USERBLOCKEDNOENDDATE},    '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
1702 };
1703
1704 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
1705     plan tests => 1;
1706
1707     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1708     my $patron_category_x = $builder->build_object(
1709         {
1710             class => 'Koha::Patron::Categories',
1711             value => { category_type => 'X' }
1712         }
1713     );
1714     my $patron = $builder->build_object(
1715         {
1716             class => 'Koha::Patrons',
1717             value => {
1718                 categorycode  => $patron_category_x->categorycode,
1719                 gonenoaddress => undef,
1720                 lost          => undef,
1721                 debarred      => undef,
1722                 borrowernotes => ""
1723             }
1724         }
1725     );
1726     my $item_1 = $builder->build_sample_item(
1727         {
1728             library => $library->{branchcode},
1729         }
1730     )->unblessed;
1731
1732     my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->{barcode} );
1733     is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
1734
1735     # TODO There are other tests to provide here
1736 };
1737
1738 subtest 'MultipleReserves' => sub {
1739     plan tests => 3;
1740
1741     my $biblio = $builder->build_sample_biblio();
1742
1743     my $branch = $library2->{branchcode};
1744
1745     my $item_1 = $builder->build_sample_item(
1746         {
1747             biblionumber     => $biblio->biblionumber,
1748             library          => $branch,
1749             replacementprice => 12.00,
1750             itype            => $itemtype,
1751         }
1752     );
1753
1754     my $item_2 = $builder->build_sample_item(
1755         {
1756             biblionumber     => $biblio->biblionumber,
1757             library          => $branch,
1758             replacementprice => 12.00,
1759             itype            => $itemtype,
1760         }
1761     );
1762
1763     my $bibitems       = '';
1764     my $priority       = '1';
1765     my $resdate        = undef;
1766     my $expdate        = undef;
1767     my $notes          = '';
1768     my $checkitem      = undef;
1769     my $found          = undef;
1770
1771     my %renewing_borrower_data = (
1772         firstname =>  'John',
1773         surname => 'Renewal',
1774         categorycode => $patron_category->{categorycode},
1775         branchcode => $branch,
1776     );
1777     my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
1778     my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
1779     my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
1780     my $datedue = dt_from_string( $issue->date_due() );
1781     is (defined $issue->date_due(), 1, "item 1 checked out");
1782     my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
1783
1784     my %reserving_borrower_data1 = (
1785         firstname =>  'Katrin',
1786         surname => 'Reservation',
1787         categorycode => $patron_category->{categorycode},
1788         branchcode => $branch,
1789     );
1790     my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
1791     AddReserve(
1792         $branch, $reserving_borrowernumber1, $biblio->biblionumber,
1793         $bibitems,  $priority, $resdate, $expdate, $notes,
1794         'a title', $checkitem, $found
1795     );
1796
1797     my %reserving_borrower_data2 = (
1798         firstname =>  'Kirk',
1799         surname => 'Reservation',
1800         categorycode => $patron_category->{categorycode},
1801         branchcode => $branch,
1802     );
1803     my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
1804     AddReserve(
1805         $branch, $reserving_borrowernumber2, $biblio->biblionumber,
1806         $bibitems,  $priority, $resdate, $expdate, $notes,
1807         'a title', $checkitem, $found
1808     );
1809
1810     {
1811         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1812         is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
1813     }
1814
1815     my $item_3 = $builder->build_sample_item(
1816         {
1817             biblionumber     => $biblio->biblionumber,
1818             library          => $branch,
1819             replacementprice => 12.00,
1820             itype            => $itemtype,
1821         }
1822     );
1823
1824     {
1825         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1826         is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
1827     }
1828 };
1829
1830 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
1831     plan tests => 5;
1832
1833     my $library = $builder->build( { source => 'Branch' } );
1834     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1835
1836     my $biblionumber = $builder->build_sample_biblio(
1837         {
1838             branchcode => $library->{branchcode},
1839         }
1840     )->biblionumber;
1841     my $item_1 = $builder->build_sample_item(
1842         {
1843             biblionumber => $biblionumber,
1844             library      => $library->{branchcode},
1845         }
1846     )->unblessed;
1847
1848     my $item_2 = $builder->build_sample_item(
1849         {
1850             biblionumber => $biblionumber,
1851             library      => $library->{branchcode},
1852         }
1853     )->unblessed;
1854
1855     my ( $error, $question, $alerts );
1856     my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, dt_from_string->add( days => 1 ) );
1857
1858     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1859     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1860     cmp_deeply(
1861         { error => $error, alerts => $alerts },
1862         { error => {}, alerts => {} },
1863         'No error or alert should be raised'
1864     );
1865     is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' );
1866
1867     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1868     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1869     cmp_deeply(
1870         { error => $error, question => $question, alerts => $alerts },
1871         { error => {}, question => {}, alerts => {} },
1872         'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1'
1873     );
1874
1875     # Add a subscription
1876     Koha::Subscription->new({ biblionumber => $biblionumber })->store;
1877
1878     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1879     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1880     cmp_deeply(
1881         { error => $error, question => $question, alerts => $alerts },
1882         { error => {}, question => {}, alerts => {} },
1883         'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
1884     );
1885
1886     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1887     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1888     cmp_deeply(
1889         { error => $error, question => $question, alerts => $alerts },
1890         { error => {}, question => {}, alerts => {} },
1891         'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
1892     );
1893 };
1894
1895 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
1896     plan tests => 8;
1897
1898     my $library = $builder->build( { source => 'Branch' } );
1899     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1900
1901     # Add 2 items
1902     my $biblionumber = $builder->build_sample_biblio(
1903         {
1904             branchcode => $library->{branchcode},
1905         }
1906     )->biblionumber;
1907     my $item_1 = $builder->build_sample_item(
1908         {
1909             biblionumber => $biblionumber,
1910             library      => $library->{branchcode},
1911         }
1912     )->unblessed;
1913     my $item_2 = $builder->build_sample_item(
1914         {
1915             biblionumber => $biblionumber,
1916             library      => $library->{branchcode},
1917         }
1918     )->unblessed;
1919
1920     # And the circulation rule
1921     Koha::CirculationRules->search->delete;
1922     Koha::CirculationRules->set_rules(
1923         {
1924             categorycode => undef,
1925             itemtype     => undef,
1926             branchcode   => undef,
1927             rules        => {
1928                 issuelength => 1,
1929                 firstremind => 1,        # 1 day of grace
1930                 finedays    => 2,        # 2 days of fine per day of overdue
1931                 lengthunit  => 'days',
1932             }
1933         }
1934     );
1935
1936     # Patron cannot issue item_1, they have overdues
1937     my $five_days_ago = dt_from_string->subtract( days => 5 );
1938     my $ten_days_ago  = dt_from_string->subtract( days => 10 );
1939     AddIssue( $patron, $item_1->{barcode}, $five_days_ago );    # Add an overdue
1940     AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1941       ;    # Add another overdue
1942
1943     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
1944     AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, dt_from_string );
1945     my $debarments = Koha::Patron::Debarments::GetDebarments(
1946         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1947     is( scalar(@$debarments), 1 );
1948
1949     # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
1950     # Same for the others
1951     my $expected_expiration = output_pref(
1952         {
1953             dt         => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1954             dateformat => 'sql',
1955             dateonly   => 1
1956         }
1957     );
1958     is( $debarments->[0]->{expiration}, $expected_expiration );
1959
1960     AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, dt_from_string );
1961     $debarments = Koha::Patron::Debarments::GetDebarments(
1962         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1963     is( scalar(@$debarments), 1 );
1964     $expected_expiration = output_pref(
1965         {
1966             dt         => dt_from_string->add( days => ( 10 - 1 ) * 2 ),
1967             dateformat => 'sql',
1968             dateonly   => 1
1969         }
1970     );
1971     is( $debarments->[0]->{expiration}, $expected_expiration );
1972
1973     Koha::Patron::Debarments::DelUniqueDebarment(
1974         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1975
1976     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
1977     AddIssue( $patron, $item_1->{barcode}, $five_days_ago );    # Add an overdue
1978     AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1979       ;    # Add another overdue
1980     AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, dt_from_string );
1981     $debarments = Koha::Patron::Debarments::GetDebarments(
1982         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1983     is( scalar(@$debarments), 1 );
1984     $expected_expiration = output_pref(
1985         {
1986             dt         => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1987             dateformat => 'sql',
1988             dateonly   => 1
1989         }
1990     );
1991     is( $debarments->[0]->{expiration}, $expected_expiration );
1992
1993     AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, dt_from_string );
1994     $debarments = Koha::Patron::Debarments::GetDebarments(
1995         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1996     is( scalar(@$debarments), 1 );
1997     $expected_expiration = output_pref(
1998         {
1999             dt => dt_from_string->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
2000             dateformat => 'sql',
2001             dateonly   => 1
2002         }
2003     );
2004     is( $debarments->[0]->{expiration}, $expected_expiration );
2005 };
2006
2007 subtest 'AddReturn + suspension_chargeperiod' => sub {
2008     plan tests => 21;
2009
2010     my $library = $builder->build( { source => 'Branch' } );
2011     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2012
2013     my $biblionumber = $builder->build_sample_biblio(
2014         {
2015             branchcode => $library->{branchcode},
2016         }
2017     )->biblionumber;
2018     my $item_1 = $builder->build_sample_item(
2019         {
2020             biblionumber => $biblionumber,
2021             library      => $library->{branchcode},
2022         }
2023     )->unblessed;
2024
2025     # And the issuing rule
2026     Koha::IssuingRules->search->delete;
2027     my $rule = Koha::IssuingRule->new(
2028         {
2029             categorycode => '*',
2030             itemtype     => '*',
2031             branchcode   => '*',
2032             issuelength  => 1,
2033             firstremind  => 0,        # 0 day of grace
2034             finedays     => 2,        # 2 days of fine per day of overdue
2035             suspension_chargeperiod => 1,
2036             lengthunit   => 'days',
2037         }
2038     );
2039     $rule->store();
2040
2041     my $five_days_ago = dt_from_string->subtract( days => 5 );
2042     # We want to charge 2 days every day, without grace
2043     # With 5 days of overdue: 5 * Z
2044     my $expected_expiration = dt_from_string->add( days => ( 5 * 2 ) / 1 );
2045     test_debarment_on_checkout(
2046         {
2047             item            => $item_1,
2048             library         => $library,
2049             patron          => $patron,
2050             due_date        => $five_days_ago,
2051             expiration_date => $expected_expiration,
2052         }
2053     );
2054
2055     # We want to charge 2 days every 2 days, without grace
2056     # With 5 days of overdue: (5 * 2) / 2
2057     $rule->suspension_chargeperiod(2)->store;
2058     $expected_expiration = dt_from_string->add( days => floor( 5 * 2 ) / 2 );
2059     test_debarment_on_checkout(
2060         {
2061             item            => $item_1,
2062             library         => $library,
2063             patron          => $patron,
2064             due_date        => $five_days_ago,
2065             expiration_date => $expected_expiration,
2066         }
2067     );
2068
2069     # We want to charge 2 days every 3 days, with 1 day of grace
2070     # With 5 days of overdue: ((5-1) / 3 ) * 2
2071     $rule->suspension_chargeperiod(3)->store;
2072     $rule->firstremind(1)->store;
2073     $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
2074     test_debarment_on_checkout(
2075         {
2076             item            => $item_1,
2077             library         => $library,
2078             patron          => $patron,
2079             due_date        => $five_days_ago,
2080             expiration_date => $expected_expiration,
2081         }
2082     );
2083
2084     # Use finesCalendar to know if holiday must be skipped to calculate the due date
2085     # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
2086     $rule->finedays(2)->store;
2087     $rule->suspension_chargeperiod(1)->store;
2088     $rule->firstremind(0)->store;
2089     t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
2090     t::lib::Mocks::mock_preference('SuspensionsCalendar', 'noSuspensionsWhenClosed');
2091
2092     # Adding a holiday 2 days ago
2093     my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
2094     my $two_days_ago = dt_from_string->subtract( days => 2 );
2095     $calendar->insert_single_holiday(
2096         day             => $two_days_ago->day,
2097         month           => $two_days_ago->month,
2098         year            => $two_days_ago->year,
2099         title           => 'holidayTest-2d',
2100         description     => 'holidayDesc 2 days ago'
2101     );
2102     # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
2103     $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
2104     test_debarment_on_checkout(
2105         {
2106             item            => $item_1,
2107             library         => $library,
2108             patron          => $patron,
2109             due_date        => $five_days_ago,
2110             expiration_date => $expected_expiration,
2111         }
2112     );
2113
2114     # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
2115     my $two_days_ahead = dt_from_string->add( days => 2 );
2116     $calendar->insert_single_holiday(
2117         day             => $two_days_ahead->day,
2118         month           => $two_days_ahead->month,
2119         year            => $two_days_ahead->year,
2120         title           => 'holidayTest+2d',
2121         description     => 'holidayDesc 2 days ahead'
2122     );
2123
2124     # Same as above, but we should skip D+2
2125     $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
2126     test_debarment_on_checkout(
2127         {
2128             item            => $item_1,
2129             library         => $library,
2130             patron          => $patron,
2131             due_date        => $five_days_ago,
2132             expiration_date => $expected_expiration,
2133         }
2134     );
2135
2136     # Adding another holiday, day of expiration date
2137     my $expected_expiration_dt = dt_from_string($expected_expiration);
2138     $calendar->insert_single_holiday(
2139         day             => $expected_expiration_dt->day,
2140         month           => $expected_expiration_dt->month,
2141         year            => $expected_expiration_dt->year,
2142         title           => 'holidayTest_exp',
2143         description     => 'holidayDesc on expiration date'
2144     );
2145     # Expiration date will be the day after
2146     test_debarment_on_checkout(
2147         {
2148             item            => $item_1,
2149             library         => $library,
2150             patron          => $patron,
2151             due_date        => $five_days_ago,
2152             expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
2153         }
2154     );
2155
2156     test_debarment_on_checkout(
2157         {
2158             item            => $item_1,
2159             library         => $library,
2160             patron          => $patron,
2161             return_date     => dt_from_string->add(days => 5),
2162             expiration_date => dt_from_string->add(days => 5 + (5 * 2 - 1) ),
2163         }
2164     );
2165 };
2166
2167 subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
2168     plan tests => 2;
2169
2170     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2171     my $patron1 = $builder->build_object(
2172         {
2173             class => 'Koha::Patrons',
2174             value => {
2175                 library      => $library->branchcode,
2176                 categorycode => $patron_category->{categorycode}
2177             }
2178         }
2179     );
2180     my $patron2 = $builder->build_object(
2181         {
2182             class => 'Koha::Patrons',
2183             value => {
2184                 library      => $library->branchcode,
2185                 categorycode => $patron_category->{categorycode}
2186             }
2187         }
2188     );
2189
2190     t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
2191
2192     my $item = $builder->build_sample_item(
2193         {
2194             library      => $library->branchcode,
2195         }
2196     )->unblessed;
2197
2198     my ( $error, $question, $alerts );
2199     my $issue = AddIssue( $patron1->unblessed, $item->{barcode} );
2200
2201     t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2202     ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->{barcode} );
2203     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' );
2204
2205     t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
2206     ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->{barcode} );
2207     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' );
2208
2209     t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2210 };
2211
2212
2213 subtest 'AddReturn | is_overdue' => sub {
2214     plan tests => 5;
2215
2216     t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
2217     t::lib::Mocks::mock_preference('finesMode', 'production');
2218     t::lib::Mocks::mock_preference('MaxFine', '100');
2219
2220     my $library = $builder->build( { source => 'Branch' } );
2221     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2222     my $manager = $builder->build_object({ class => "Koha::Patrons" });
2223     t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2224
2225     my $item = $builder->build_sample_item(
2226         {
2227             library      => $library->{branchcode},
2228             replacementprice => 7
2229         }
2230     )->unblessed;
2231
2232     Koha::CirculationRules->search->delete;
2233     my $rule = Koha::CirculationRules->set_rules(
2234         {
2235             categorycode => undef,
2236             itemtype     => undef,
2237             branchcode   => undef,
2238             rules        => {
2239                 issuelength  => 6,
2240                 lengthunit   => 'days',
2241                 fine         => 1,        # Charge 1 every day of overdue
2242                 chargeperiod => 1,
2243             }
2244         }
2245     );
2246
2247     my $now   = dt_from_string;
2248     my $one_day_ago   = dt_from_string->subtract( days => 1 );
2249     my $five_days_ago = dt_from_string->subtract( days => 5 );
2250     my $ten_days_ago  = dt_from_string->subtract( days => 10 );
2251     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
2252
2253     # No return date specified, today will be used => 10 days overdue charged
2254     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2255     AddReturn( $item->{barcode}, $library->{branchcode} );
2256     is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
2257     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2258
2259     # specify return date 5 days before => no overdue charged
2260     AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
2261     AddReturn( $item->{barcode}, $library->{branchcode}, undef, $ten_days_ago );
2262     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2263     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2264
2265     # specify return date 5 days later => 5 days overdue charged
2266     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2267     AddReturn( $item->{barcode}, $library->{branchcode}, undef, $five_days_ago );
2268     is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
2269     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2270
2271     # specify return date 5 days later, specify exemptfine => no overdue charge
2272     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2273     AddReturn( $item->{barcode}, $library->{branchcode}, 1, $five_days_ago );
2274     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2275     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2276
2277     subtest 'bug 22877' => sub {
2278
2279         plan tests => 3;
2280
2281         my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago );    # date due was 10d ago
2282
2283         # Fake fines cronjob on this checkout
2284         my ($fine) =
2285           CalcFine( $item, $patron->categorycode, $library->{branchcode},
2286             $ten_days_ago, $now );
2287         UpdateFine(
2288             {
2289                 issue_id       => $issue->issue_id,
2290                 itemnumber     => $item->{itemnumber},
2291                 borrowernumber => $patron->borrowernumber,
2292                 amount         => $fine,
2293                 due            => output_pref($ten_days_ago)
2294             }
2295         );
2296         is( int( $patron->account->balance() ),
2297             10, "Overdue fine of 10 days overdue" );
2298
2299         # Fake longoverdue with charge and not marking returned
2300         LostItem( $item->{itemnumber}, 'cronjob', 0 );
2301         is( int( $patron->account->balance() ),
2302             17, "Lost fine of 7 plus 10 days overdue" );
2303
2304         # Now we return it today
2305         AddReturn( $item->{barcode}, $library->{branchcode} );
2306         is( int( $patron->account->balance() ),
2307             17, "Should have a single 10 days overdue fine and lost charge" );
2308       }
2309 };
2310
2311 subtest '_FixAccountForLostAndReturned' => sub {
2312
2313     plan tests => 5;
2314
2315     t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
2316     t::lib::Mocks::mock_preference( 'WhenLostForgiveFine',          0 );
2317
2318     my $processfee_amount  = 20;
2319     my $replacement_amount = 99.00;
2320     my $item_type          = $builder->build_object(
2321         {   class => 'Koha::ItemTypes',
2322             value => {
2323                 notforloan         => undef,
2324                 rentalcharge       => 0,
2325                 defaultreplacecost => undef,
2326                 processfee         => $processfee_amount,
2327                 rentalcharge_daily => 0,
2328             }
2329         }
2330     );
2331     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2332
2333     my $biblio = $builder->build_sample_biblio({ author => 'Hall, Daria' });
2334
2335     subtest 'Full write-off tests' => sub {
2336
2337         plan tests => 12;
2338
2339         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2340         my $manager = $builder->build_object({ class => "Koha::Patrons" });
2341         t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
2342
2343         my $item = $builder->build_sample_item(
2344             {
2345                 biblionumber     => $biblio->biblionumber,
2346                 library          => $library->branchcode,
2347                 replacementprice => $replacement_amount,
2348                 itype            => $item_type->itemtype,
2349             }
2350         );
2351
2352         AddIssue( $patron->unblessed, $item->barcode );
2353
2354         # Simulate item marked as lost
2355         ModItem( { itemlost => 3 }, $biblio->biblionumber, $item->itemnumber );
2356         LostItem( $item->itemnumber, 1 );
2357
2358         my $processing_fee_lines = Koha::Account::Lines->search(
2359             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2360         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2361         my $processing_fee_line = $processing_fee_lines->next;
2362         is( $processing_fee_line->amount + 0,
2363             $processfee_amount, 'The right PROCESSING amount is generated' );
2364         is( $processing_fee_line->amountoutstanding + 0,
2365             $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2366
2367         my $lost_fee_lines = Koha::Account::Lines->search(
2368             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2369         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2370         my $lost_fee_line = $lost_fee_lines->next;
2371         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2372         is( $lost_fee_line->amountoutstanding + 0,
2373             $replacement_amount, 'The right LOST amountoutstanding is generated' );
2374         is( $lost_fee_line->status,
2375             undef, 'The LOST status was not set' );
2376
2377         my $account = $patron->account;
2378         my $debts   = $account->outstanding_debits;
2379
2380         # Write off the debt
2381         my $credit = $account->add_credit(
2382             {   amount => $account->balance,
2383                 type   => 'WRITEOFF',
2384                 interface => 'test',
2385             }
2386         );
2387         $credit->apply( { debits => [ $debts->as_list ], offset_type => 'Writeoff' } );
2388
2389         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2390         is( $credit_return_id, undef, 'No LOST_RETURN account line added' );
2391
2392         $lost_fee_line->discard_changes; # reload from DB
2393         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2394         is( $lost_fee_line->debit_type_code,
2395             'LOST', 'Lost fee now still has account type of LOST' );
2396         is( $lost_fee_line->status, 'RETURNED', "Lost fee now has account status of RETURNED");
2397
2398         is( $patron->account->balance, -0, 'The patron balance is 0, everything was written off' );
2399     };
2400
2401     subtest 'Full payment tests' => sub {
2402
2403         plan tests => 13;
2404
2405         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2406
2407         my $item = $builder->build_sample_item(
2408             {
2409                 biblionumber     => $biblio->biblionumber,
2410                 library          => $library->branchcode,
2411                 replacementprice => $replacement_amount,
2412                 itype            => $item_type->itemtype
2413             }
2414         );
2415
2416         AddIssue( $patron->unblessed, $item->barcode );
2417
2418         # Simulate item marked as lost
2419         ModItem( { itemlost => 1 }, $biblio->biblionumber, $item->itemnumber );
2420         LostItem( $item->itemnumber, 1 );
2421
2422         my $processing_fee_lines = Koha::Account::Lines->search(
2423             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2424         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2425         my $processing_fee_line = $processing_fee_lines->next;
2426         is( $processing_fee_line->amount + 0,
2427             $processfee_amount, 'The right PROCESSING amount is generated' );
2428         is( $processing_fee_line->amountoutstanding + 0,
2429             $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2430
2431         my $lost_fee_lines = Koha::Account::Lines->search(
2432             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2433         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2434         my $lost_fee_line = $lost_fee_lines->next;
2435         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2436         is( $lost_fee_line->amountoutstanding + 0,
2437             $replacement_amount, 'The right LOST amountountstanding is generated' );
2438
2439         my $account = $patron->account;
2440         my $debts   = $account->outstanding_debits;
2441
2442         # Write off the debt
2443         my $credit = $account->add_credit(
2444             {   amount => $account->balance,
2445                 type   => 'PAYMENT',
2446                 interface => 'test',
2447             }
2448         );
2449         $credit->apply( { debits => [ $debts->as_list ], offset_type => 'Payment' } );
2450
2451         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2452         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2453
2454         is( $credit_return->credit_type_code, 'LOST_RETURN', 'An account line of type LOST_RETURN is added' );
2455         is( $credit_return->amount + 0,
2456             -99.00, 'The account line of type LOST_RETURN has an amount of -99' );
2457         is( $credit_return->amountoutstanding + 0,
2458             -99.00, 'The account line of type LOST_RETURN has an amountoutstanding of -99' );
2459
2460         $lost_fee_line->discard_changes;
2461         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2462         is( $lost_fee_line->debit_type_code,
2463             'LOST', 'Lost fee now still has account type of LOST' );
2464         is( $lost_fee_line->status, 'RETURNED', "Lost fee now has account status of RETURNED");
2465
2466         is( $patron->account->balance,
2467             -99, 'The patron balance is -99, a credit that equals the lost fee payment' );
2468     };
2469
2470     subtest 'Test without payment or write off' => sub {
2471
2472         plan tests => 13;
2473
2474         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2475
2476         my $item = $builder->build_sample_item(
2477             {
2478                 biblionumber     => $biblio->biblionumber,
2479                 library          => $library->branchcode,
2480                 replacementprice => 23.00,
2481                 replacementprice => $replacement_amount,
2482                 itype            => $item_type->itemtype
2483             }
2484         );
2485
2486         AddIssue( $patron->unblessed, $item->barcode );
2487
2488         # Simulate item marked as lost
2489         ModItem( { itemlost => 3 }, $biblio->biblionumber, $item->itemnumber );
2490         LostItem( $item->itemnumber, 1 );
2491
2492         my $processing_fee_lines = Koha::Account::Lines->search(
2493             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2494         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2495         my $processing_fee_line = $processing_fee_lines->next;
2496         is( $processing_fee_line->amount + 0,
2497             $processfee_amount, 'The right PROCESSING amount is generated' );
2498         is( $processing_fee_line->amountoutstanding + 0,
2499             $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2500
2501         my $lost_fee_lines = Koha::Account::Lines->search(
2502             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2503         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2504         my $lost_fee_line = $lost_fee_lines->next;
2505         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2506         is( $lost_fee_line->amountoutstanding + 0,
2507             $replacement_amount, 'The right LOST amountountstanding is generated' );
2508
2509         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2510         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2511
2512         is( $credit_return->credit_type_code, 'LOST_RETURN', 'An account line of type LOST_RETURN is added' );
2513         is( $credit_return->amount + 0, -99.00, 'The account line of type LOST_RETURN has an amount of -99' );
2514         is( $credit_return->amountoutstanding + 0, 0, 'The account line of type LOST_RETURN has an amountoutstanding of 0' );
2515
2516         $lost_fee_line->discard_changes;
2517         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2518         is( $lost_fee_line->debit_type_code,
2519             'LOST', 'Lost fee now still has account type of LOST' );
2520         is( $lost_fee_line->status, 'RETURNED', "Lost fee now has account status of RETURNED");
2521
2522         is( $patron->account->balance, 20, 'The patron balance is 20, still owes the processing fee' );
2523     };
2524
2525     subtest 'Test with partial payement and write off, and remaining debt' => sub {
2526
2527         plan tests => 16;
2528
2529         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2530         my $item = $builder->build_sample_item(
2531             {
2532                 biblionumber     => $biblio->biblionumber,
2533                 library          => $library->branchcode,
2534                 replacementprice => $replacement_amount,
2535                 itype            => $item_type->itemtype
2536             }
2537         );
2538
2539         AddIssue( $patron->unblessed, $item->barcode );
2540
2541         # Simulate item marked as lost
2542         ModItem( { itemlost => 1 }, $biblio->biblionumber, $item->itemnumber );
2543         LostItem( $item->itemnumber, 1 );
2544
2545         my $processing_fee_lines = Koha::Account::Lines->search(
2546             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2547         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2548         my $processing_fee_line = $processing_fee_lines->next;
2549         is( $processing_fee_line->amount + 0,
2550             $processfee_amount, 'The right PROCESSING amount is generated' );
2551         is( $processing_fee_line->amountoutstanding + 0,
2552             $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2553
2554         my $lost_fee_lines = Koha::Account::Lines->search(
2555             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2556         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2557         my $lost_fee_line = $lost_fee_lines->next;
2558         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2559         is( $lost_fee_line->amountoutstanding + 0,
2560             $replacement_amount, 'The right LOST amountountstanding is generated' );
2561
2562         my $account = $patron->account;
2563         is( $account->balance, $processfee_amount + $replacement_amount, 'Balance is PROCESSING + L' );
2564
2565         # Partially pay fee
2566         my $payment_amount = 27;
2567         my $payment        = $account->add_credit(
2568             {   amount => $payment_amount,
2569                 type   => 'PAYMENT',
2570                 interface => 'test',
2571             }
2572         );
2573
2574         $payment->apply( { debits => [ $lost_fee_line ], offset_type => 'Payment' } );
2575
2576         # Partially write off fee
2577         my $write_off_amount = 25;
2578         my $write_off        = $account->add_credit(
2579             {   amount => $write_off_amount,
2580                 type   => 'WRITEOFF',
2581                 interface => 'test',
2582             }
2583         );
2584         $write_off->apply( { debits => [ $lost_fee_line ], offset_type => 'Writeoff' } );
2585
2586         is( $account->balance,
2587             $processfee_amount + $replacement_amount - $payment_amount - $write_off_amount,
2588             'Payment and write off applied'
2589         );
2590
2591         # Store the amountoutstanding value
2592         $lost_fee_line->discard_changes;
2593         my $outstanding = $lost_fee_line->amountoutstanding;
2594
2595         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2596         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2597
2598         is( $account->balance, $processfee_amount - $payment_amount, 'Balance is PROCESSING - PAYMENT (LOST_RETURN)' );
2599
2600         $lost_fee_line->discard_changes;
2601         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2602         is( $lost_fee_line->debit_type_code,
2603             'LOST', 'Lost fee now still has account type of LOST' );
2604         is( $lost_fee_line->status, 'RETURNED', "Lost fee now has account status of RETURNED");
2605
2606         is( $credit_return->credit_type_code, 'LOST_RETURN', 'An account line of type LOST_RETURN is added' );
2607         is( $credit_return->amount + 0,
2608             ($payment_amount + $outstanding ) * -1,
2609             'The account line of type LOST_RETURN has an amount equal to the payment + outstanding'
2610         );
2611         is( $credit_return->amountoutstanding + 0,
2612             $payment_amount * -1,
2613             'The account line of type LOST_RETURN has an amountoutstanding equal to the payment'
2614         );
2615
2616         is( $account->balance,
2617             $processfee_amount - $payment_amount,
2618             'The patron balance is the difference between the PROCESSING and the credit'
2619         );
2620     };
2621
2622     subtest 'Partial payement, existing debits and AccountAutoReconcile' => sub {
2623
2624         plan tests => 8;
2625
2626         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2627         my $barcode = 'KD123456793';
2628         my $replacement_amount = 100;
2629         my $processfee_amount  = 20;
2630
2631         my $item_type          = $builder->build_object(
2632             {   class => 'Koha::ItemTypes',
2633                 value => {
2634                     notforloan         => undef,
2635                     rentalcharge       => 0,
2636                     defaultreplacecost => undef,
2637                     processfee         => 0,
2638                     rentalcharge_daily => 0,
2639                 }
2640             }
2641         );
2642         my ( undef, undef, $item_id ) = AddItem(
2643             {   homebranch       => $library->branchcode,
2644                 holdingbranch    => $library->branchcode,
2645                 barcode          => $barcode,
2646                 replacementprice => $replacement_amount,
2647                 itype            => $item_type->itemtype
2648             },
2649             $biblio->biblionumber
2650         );
2651
2652         AddIssue( $patron->unblessed, $barcode );
2653
2654         # Simulate item marked as lost
2655         ModItem( { itemlost => 1 }, $biblio->biblionumber, $item_id );
2656         LostItem( $item_id, 1 );
2657
2658         my $lost_fee_lines = Koha::Account::Lines->search(
2659             { borrowernumber => $patron->id, itemnumber => $item_id, debit_type_code => 'LOST' } );
2660         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2661         my $lost_fee_line = $lost_fee_lines->next;
2662         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2663         is( $lost_fee_line->amountoutstanding + 0,
2664             $replacement_amount, 'The right LOST amountountstanding is generated' );
2665
2666         my $account = $patron->account;
2667         is( $account->balance, $replacement_amount, 'Balance is L' );
2668
2669         # Partially pay fee
2670         my $payment_amount = 27;
2671         my $payment        = $account->add_credit(
2672             {   amount => $payment_amount,
2673                 type   => 'PAYMENT',
2674                 interface => 'test',
2675             }
2676         );
2677         $payment->apply({ debits => [ $lost_fee_line ], offset_type => 'Payment' });
2678
2679         is( $account->balance,
2680             $replacement_amount - $payment_amount,
2681             'Payment applied'
2682         );
2683
2684         my $manual_debit_amount = 80;
2685         $account->add_debit( { amount => $manual_debit_amount, type => 'OVERDUE', interface =>'test' } );
2686
2687         is( $account->balance, $manual_debit_amount + $replacement_amount - $payment_amount, 'Manual debit applied' );
2688
2689         t::lib::Mocks::mock_preference( 'AccountAutoReconcile', 1 );
2690
2691         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item_id, $patron->id );
2692         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2693
2694         is( $account->balance, $manual_debit_amount - $payment_amount, 'Balance is PROCESSING - payment (LOST_RETURN)' );
2695
2696         my $manual_debit = Koha::Account::Lines->search({ borrowernumber => $patron->id, debit_type_code => 'OVERDUE', status => 'UNRETURNED' })->next;
2697         is( $manual_debit->amountoutstanding + 0, $manual_debit_amount - $payment_amount, 'reconcile_balance was called' );
2698     };
2699 };
2700
2701 subtest '_FixOverduesOnReturn' => sub {
2702     plan tests => 11;
2703
2704     my $manager = $builder->build_object({ class => "Koha::Patrons" });
2705     t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2706
2707     my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
2708
2709     my $branchcode  = $library2->{branchcode};
2710
2711     my $item = $builder->build_sample_item(
2712         {
2713             biblionumber     => $biblio->biblionumber,
2714             library          => $branchcode,
2715             replacementprice => 99.00,
2716             itype            => $itemtype,
2717         }
2718     );
2719
2720     my $patron = $builder->build( { source => 'Borrower' } );
2721
2722     ## Start with basic call, should just close out the open fine
2723     my $accountline = Koha::Account::Line->new(
2724         {
2725             borrowernumber => $patron->{borrowernumber},
2726             debit_type_code    => 'OVERDUE',
2727             status         => 'UNRETURNED',
2728             itemnumber     => $item->itemnumber,
2729             amount => 99.00,
2730             amountoutstanding => 99.00,
2731             interface => 'test',
2732         }
2733     )->store();
2734
2735     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, undef, 'RETURNED' );
2736
2737     $accountline->_result()->discard_changes();
2738
2739     is( $accountline->amountoutstanding+0, 99, 'Fine has the same amount outstanding as previously' );
2740     isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
2741     is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
2742
2743     ## Run again, with exemptfine enabled
2744     $accountline->set(
2745         {
2746             debit_type_code    => 'OVERDUE',
2747             status         => 'UNRETURNED',
2748             amountoutstanding => 99.00,
2749         }
2750     )->store();
2751
2752     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
2753
2754     $accountline->_result()->discard_changes();
2755     my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
2756
2757     is( $accountline->amountoutstanding + 0, 0, 'Fine amountoutstanding has been reduced to 0' );
2758     isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
2759     is( $accountline->status, 'FORGIVEN', 'Open fine ( account type OVERDUE ) has been set to fine forgiven ( status FORGIVEN )');
2760     is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
2761     is( $offset->amount + 0, -99, "Amount of offset is correct" );
2762     my $credit = $offset->credit;
2763     is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
2764     is( $credit->amount + 0, -99, "Credit amount is set correctly" );
2765     is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
2766 };
2767
2768 subtest '_FixAccountForLostAndReturned returns undef if patron is deleted' => sub {
2769     plan tests => 1;
2770
2771     my $manager = $builder->build_object({ class => "Koha::Patrons" });
2772     t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2773
2774     my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
2775
2776     my $branchcode  = $library2->{branchcode};
2777
2778     my $item = $builder->build_sample_item(
2779         {
2780             biblionumber     => $biblio->biblionumber,
2781             library          => $branchcode,
2782             replacementprice => 99.00,
2783             itype            => $itemtype,
2784         }
2785     );
2786
2787     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2788
2789     ## Start with basic call, should just close out the open fine
2790     my $accountline = Koha::Account::Line->new(
2791         {
2792             borrowernumber => $patron->id,
2793             debit_type_code    => 'LOST',
2794             status         => undef,
2795             itemnumber     => $item->itemnumber,
2796             amount => 99.00,
2797             amountoutstanding => 99.00,
2798             interface => 'test',
2799         }
2800     )->store();
2801
2802     $patron->delete();
2803
2804     my $return_value = C4::Circulation::_FixAccountForLostAndReturned( $patron->id, $item->itemnumber );
2805
2806     is( $return_value, undef, "_FixAccountForLostAndReturned returns undef if patron is deleted" );
2807
2808 };
2809
2810 subtest 'Set waiting flag' => sub {
2811     plan tests => 4;
2812
2813     my $library_1 = $builder->build( { source => 'Branch' } );
2814     my $patron_1  = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2815     my $library_2 = $builder->build( { source => 'Branch' } );
2816     my $patron_2  = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2817
2818     my $item = $builder->build_sample_item(
2819         {
2820             library      => $library_1->{branchcode},
2821         }
2822     )->unblessed;
2823
2824     set_userenv( $library_2 );
2825     my $reserve_id = AddReserve(
2826         $library_2->{branchcode}, $patron_2->{borrowernumber}, $item->{biblionumber},
2827         '', 1, undef, undef, '', undef, $item->{itemnumber},
2828     );
2829
2830     set_userenv( $library_1 );
2831     my $do_transfer = 1;
2832     my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
2833     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2834     my $hold = Koha::Holds->find( $reserve_id );
2835     is( $hold->found, 'T', 'Hold is in transit' );
2836
2837     my ( $status ) = CheckReserves($item->{itemnumber});
2838     is( $status, 'Reserved', 'Hold is not waiting yet');
2839
2840     set_userenv( $library_2 );
2841     $do_transfer = 0;
2842     AddReturn( $item->{barcode}, $library_2->{branchcode} );
2843     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2844     $hold = Koha::Holds->find( $reserve_id );
2845     is( $hold->found, 'W', 'Hold is waiting' );
2846     ( $status ) = CheckReserves($item->{itemnumber});
2847     is( $status, 'Waiting', 'Now the hold is waiting');
2848 };
2849
2850 subtest 'Cancel transfers on lost items' => sub {
2851     plan tests => 5;
2852     my $library_1 = $builder->build( { source => 'Branch' } );
2853     my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2854     my $library_2 = $builder->build( { source => 'Branch' } );
2855     my $patron_2  = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2856     my $biblio = $builder->build_sample_biblio({branchcode => $library->{branchcode}});
2857     my $item   = $builder->build_sample_item({
2858         biblionumber  => $biblio->biblionumber,
2859         library    => $library_1->{branchcode},
2860     });
2861
2862     set_userenv( $library_2 );
2863     my $reserve_id = AddReserve(
2864         $library_2->{branchcode}, $patron_2->{borrowernumber}, $item->biblionumber, '', 1, undef, undef, '', undef, $item->itemnumber,
2865     );
2866
2867     #Return book and add transfer
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     C4::Circulation::transferbook( $library_2->{branchcode}, $item->barcode );
2873     my $hold = Koha::Holds->find( $reserve_id );
2874     is( $hold->found, 'T', 'Hold is in transit' );
2875
2876     #Check transfer exists and the items holding branch is the transfer destination branch before marking it as lost
2877     my ($datesent,$frombranch,$tobranch) = GetTransfers($item->itemnumber);
2878     is( $tobranch, $library_2->{branchcode}, 'The transfer record exists in the branchtransfers table');
2879     my $itemcheck = Koha::Items->find($item->itemnumber);
2880     is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Items holding branch is the transfers origin branch before it is marked as lost' );
2881
2882     #Simulate item being marked as lost and confirm the transfer is deleted and the items holding branch is the transfers source branch
2883     ModItem( { itemlost => 1 }, $item->biblionumber, $item->itemnumber );
2884     LostItem( $item->itemnumber, 'test', 1 );
2885     ($datesent,$frombranch,$tobranch) = GetTransfers($item->itemnumber);
2886     is( $tobranch, undef, 'The transfer on the lost item has been deleted as the LostItemCancelOutstandingTransfer is enabled');
2887     $itemcheck = Koha::Items->find($item->itemnumber);
2888     is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Lost item with cancelled hold has holding branch equallying the transfers source branch' );
2889 };
2890
2891 subtest 'CanBookBeIssued | is_overdue' => sub {
2892     plan tests => 3;
2893
2894     # Set a simple circ policy
2895     $dbh->do('DELETE FROM issuingrules');
2896     $dbh->do(
2897     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
2898                                     issuelength, lengthunit,
2899                                     renewalsallowed, renewalperiod,
2900                                     norenewalbefore, auto_renew,
2901                                     fine, chargeperiod)
2902           VALUES (?, ?, ?, ?,
2903                   ?, ?,
2904                   ?, ?,
2905                   ?, ?,
2906                   ?, ?
2907                  )
2908         },
2909         {},
2910         '*',   '*', '*', 25,
2911         14,  'days',
2912         1,     7,
2913         undef, 0,
2914         .10,   1
2915     );
2916
2917     my $five_days_go = output_pref({ dt => dt_from_string->add( days => 5 ), dateonly => 1});
2918     my $ten_days_go  = output_pref({ dt => dt_from_string->add( days => 10), dateonly => 1 });
2919     my $library = $builder->build( { source => 'Branch' } );
2920     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2921
2922     my $item = $builder->build_sample_item(
2923         {
2924             library      => $library->{branchcode},
2925         }
2926     )->unblessed;
2927
2928     my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $five_days_go ); # date due was 10d ago
2929     my $actualissue = Koha::Checkouts->find( { itemnumber => $item->{itemnumber} } );
2930     is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
2931     my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->{barcode},$ten_days_go, undef, undef, undef);
2932     is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
2933     is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
2934 };
2935
2936 subtest 'ItemsDeniedRenewal preference' => sub {
2937     plan tests => 18;
2938
2939     C4::Context->set_preference('ItemsDeniedRenewal','');
2940
2941     my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
2942     $dbh->do(
2943         q{
2944         INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, issuelength, lengthunit, renewalsallowed, renewalperiod,
2945                     norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
2946         },
2947         {},
2948         '*', $idr_lib->branchcode, '*', 25,
2949         14,  'days',
2950         10,   7,
2951         undef,  0,
2952         .10, 1
2953     );
2954
2955     my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
2956         homebranch => $idr_lib->branchcode,
2957         withdrawn => 1,
2958         itype => 'HIDE',
2959         location => 'PROC',
2960         itemcallnumber => undef,
2961         itemnotes => "",
2962         }
2963     });
2964     my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
2965         homebranch => $idr_lib->branchcode,
2966         withdrawn => 0,
2967         itype => 'NOHIDE',
2968         location => 'NOPROC'
2969         }
2970     });
2971
2972     my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
2973         branchcode => $idr_lib->branchcode,
2974         }
2975     });
2976     my $future = dt_from_string->add( days => 1 );
2977     my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
2978         returndate => undef,
2979         renewals => 0,
2980         auto_renew => 0,
2981         borrowernumber => $idr_borrower->borrowernumber,
2982         itemnumber => $deny_book->itemnumber,
2983         onsite_checkout => 0,
2984         date_due => $future,
2985         }
2986     });
2987     my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
2988         returndate => undef,
2989         renewals => 0,
2990         auto_renew => 0,
2991         borrowernumber => $idr_borrower->borrowernumber,
2992         itemnumber => $allow_book->itemnumber,
2993         onsite_checkout => 0,
2994         date_due => $future,
2995         }
2996     });
2997
2998     my $idr_rules;
2999
3000     my ( $idr_mayrenew, $idr_error ) =
3001     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3002     is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
3003     is( $idr_error, undef, 'Renewal allowed when no rules' );
3004
3005     $idr_rules="withdrawn: [1]";
3006
3007     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3008     ( $idr_mayrenew, $idr_error ) =
3009     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3010     is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
3011     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
3012     ( $idr_mayrenew, $idr_error ) =
3013     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3014     is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3015     is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3016
3017     $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
3018
3019     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3020     ( $idr_mayrenew, $idr_error ) =
3021     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3022     is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
3023     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
3024     ( $idr_mayrenew, $idr_error ) =
3025     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3026     is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3027     is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3028
3029     $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
3030
3031     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3032     ( $idr_mayrenew, $idr_error ) =
3033     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3034     is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
3035     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
3036     ( $idr_mayrenew, $idr_error ) =
3037     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3038     is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
3039     is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
3040
3041     $idr_rules="itemcallnumber: [NULL]";
3042     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3043     ( $idr_mayrenew, $idr_error ) =
3044     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3045     is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
3046     $idr_rules="itemcallnumber: ['']";
3047     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3048     ( $idr_mayrenew, $idr_error ) =
3049     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3050     is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
3051
3052     $idr_rules="itemnotes: [NULL]";
3053     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3054     ( $idr_mayrenew, $idr_error ) =
3055     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3056     is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
3057     $idr_rules="itemnotes: ['']";
3058     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3059     ( $idr_mayrenew, $idr_error ) =
3060     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3061     is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
3062 };
3063
3064 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
3065     plan tests => 2;
3066
3067     t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
3068     my $library = $builder->build( { source => 'Branch' } );
3069     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
3070
3071     my $item = $builder->build_sample_item(
3072         {
3073             library      => $library->{branchcode},
3074         }
3075     );
3076
3077     my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3078     is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3079     is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3080 };
3081
3082 subtest 'CanBookBeIssued | notforloan' => sub {
3083     plan tests => 2;
3084
3085     t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
3086
3087     my $library = $builder->build( { source => 'Branch' } );
3088     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
3089
3090     my $itemtype = $builder->build(
3091         {
3092             source => 'Itemtype',
3093             value  => { notforloan => undef, }
3094         }
3095     );
3096     my $item = $builder->build_sample_item(
3097         {
3098             library  => $library->{branchcode},
3099             itype    => $itemtype->{itemtype},
3100         }
3101     );
3102     $item->biblioitem->itemtype($itemtype->{itemtype})->store;
3103
3104     my ( $issuingimpossible, $needsconfirmation );
3105
3106
3107     subtest 'item-level_itypes = 1' => sub {
3108         plan tests => 6;
3109
3110         t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
3111         # Is for loan at item type and item level
3112         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3113         is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3114         is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3115
3116         # not for loan at item type level
3117         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
3118         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3119         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3120         is_deeply(
3121             $issuingimpossible,
3122             { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
3123             'Item can not be issued, not for loan at item type level'
3124         );
3125
3126         # not for loan at item level
3127         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
3128         $item->notforloan( 1 )->store;
3129         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3130         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3131         is_deeply(
3132             $issuingimpossible,
3133             { NOT_FOR_LOAN => 1, item_notforloan => 1 },
3134             'Item can not be issued, not for loan at item type level'
3135         );
3136     };
3137
3138     subtest 'item-level_itypes = 0' => sub {
3139         plan tests => 6;
3140
3141         t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
3142
3143         # We set another itemtype for biblioitem
3144         my $itemtype = $builder->build(
3145             {
3146                 source => 'Itemtype',
3147                 value  => { notforloan => undef, }
3148             }
3149         );
3150
3151         # for loan at item type and item level
3152         $item->notforloan(0)->store;
3153         $item->biblioitem->itemtype($itemtype->{itemtype})->store;
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     # TODO test with AllowNotForLoanOverride = 1
3181 };
3182
3183 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
3184     plan tests => 1;
3185
3186     t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
3187     my $item = $builder->build_sample_item(
3188         {
3189             onloan => '2018-01-01',
3190         }
3191     );
3192
3193     AddReturn( $item->barcode, $item->homebranch );
3194     $item->discard_changes; # refresh
3195     is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
3196 };
3197
3198
3199 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
3200
3201     plan tests => 11;
3202
3203
3204     t::lib::Mocks::mock_preference('item-level_itypes', 1);
3205
3206     my $issuing_charges = 15;
3207     my $title   = 'A title';
3208     my $author  = 'Author, An';
3209     my $barcode = 'WHATARETHEODDS';
3210
3211     my $circ = Test::MockModule->new('C4::Circulation');
3212     $circ->mock(
3213         'GetIssuingCharges',
3214         sub {
3215             return $issuing_charges;
3216         }
3217     );
3218
3219     my $library  = $builder->build_object({ class => 'Koha::Libraries' });
3220     my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
3221     my $patron   = $builder->build_object({
3222         class => 'Koha::Patrons',
3223         value => { branchcode => $library->id }
3224     });
3225
3226     my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
3227     my ( undef, undef, $item_id ) = AddItem(
3228         {
3229             homebranch       => $library->id,
3230             holdingbranch    => $library->id,
3231             barcode          => $barcode,
3232             replacementprice => 23.00,
3233             itype            => $itemtype->id
3234         },
3235         $biblio->biblionumber
3236     );
3237     my $item = Koha::Items->find( $item_id );
3238
3239     my $context = Test::MockModule->new('C4::Context');
3240     $context->mock( userenv => { branch => $library->id } );
3241
3242     # Check the item out
3243     AddIssue( $patron->unblessed, $item->barcode );
3244     t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
3245     my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
3246     my %params_renewal = (
3247         timestamp => { -like => $date . "%" },
3248         module => "CIRCULATION",
3249         action => "RENEWAL",
3250     );
3251     my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
3252     AddRenewal( $patron->id, $item->id, $library->id );
3253     my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3254     is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
3255
3256     my $checkouts = $patron->checkouts;
3257     # The following will fail if run on 00:00:00
3258     unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
3259
3260     my $lines = Koha::Account::Lines->search({
3261         borrowernumber => $patron->id,
3262         itemnumber     => $item->id
3263     });
3264
3265     is( $lines->count, 2 );
3266
3267     my $line = $lines->next;
3268     is( $line->debit_type_code, 'RENT',       'The issue of item with issuing charge generates an accountline of the correct type' );
3269     is( $line->branchcode,  $library->id, 'AddIssuingCharge correctly sets branchcode' );
3270     is( $line->description, '',     'AddIssue does not set a hardcoded description for the accountline' );
3271
3272     $line = $lines->next;
3273     is( $line->debit_type_code, 'RENT_RENEW', 'The renewal of item with issuing charge generates an accountline of the correct type' );
3274     is( $line->branchcode,  $library->id, 'AddRenewal correctly sets branchcode' );
3275     is( $line->description, '', 'AddRenewal does not set a hardcoded description for the accountline' );
3276
3277     t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
3278
3279     $context = Test::MockModule->new('C4::Context');
3280     $context->mock( userenv => { branch => undef, interface => 'CRON'} ); #Test statistical logging of renewal via cron (atuo_renew)
3281
3282     $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
3283     $old_log_size = Koha::ActionLogs->count( \%params_renewal );
3284     my $sth = $dbh->prepare("SELECT COUNT(*) FROM statistics WHERE itemnumber = ? AND branch = ?");
3285     $sth->execute($item->id, $library->id);
3286     my ($old_stats_size) = $sth->fetchrow_array;
3287     AddRenewal( $patron->id, $item->id, $library->id );
3288     $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3289     $sth->execute($item->id, $library->id);
3290     my ($new_stats_size) = $sth->fetchrow_array;
3291     is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
3292     is( $new_stats_size, $old_stats_size + 1, 'renew statistic successfully added with passed branch' );
3293
3294 };
3295
3296 subtest 'ProcessOfflinePayment() tests' => sub {
3297
3298     plan tests => 4;
3299
3300
3301     my $amount = 123;
3302
3303     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
3304     my $library = $builder->build_object({ class => 'Koha::Libraries' });
3305     my $result  = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
3306
3307     is( $result, 'Success.', 'The right string is returned' );
3308
3309     my $lines = $patron->account->lines;
3310     is( $lines->count, 1, 'line created correctly');
3311
3312     my $line = $lines->next;
3313     is( $line->amount+0, $amount * -1, 'amount picked from params' );
3314     is( $line->branchcode, $library->id, 'branchcode set correctly' );
3315
3316 };
3317
3318 subtest 'Incremented fee tests' => sub {
3319     plan tests => 20;
3320
3321     my $dt = dt_from_string();
3322     Time::Fake->offset( $dt->epoch );
3323
3324     t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
3325
3326     my $library =
3327       $builder->build_object( { class => 'Koha::Libraries' } )->store;
3328
3329     my $module = new Test::MockModule('C4::Context');
3330     $module->mock( 'userenv', sub { { branch => $library->id } } );
3331
3332     my $patron = $builder->build_object(
3333         {
3334             class => 'Koha::Patrons',
3335             value => { categorycode => $patron_category->{categorycode} }
3336         }
3337     )->store;
3338
3339     my $itemtype = $builder->build_object(
3340         {
3341             class => 'Koha::ItemTypes',
3342             value => {
3343                 notforloan         => undef,
3344                 rentalcharge       => 0,
3345                 rentalcharge_daily => 1,
3346             }
3347         }
3348     )->store;
3349
3350     my $item = $builder->build_sample_item(
3351         {
3352             library  => $library->{branchcode},
3353             itype    => $itemtype->id,
3354         }
3355     );
3356
3357     is( $itemtype->rentalcharge_daily+0,
3358         1, 'Daily rental charge stored and retreived correctly' );
3359     is( $item->effective_itemtype, $itemtype->id,
3360         "Itemtype set correctly for item" );
3361
3362     my $dt_from     = dt_from_string();
3363     my $dt_to       = dt_from_string()->add( days => 7 );
3364     my $dt_to_renew = dt_from_string()->add( days => 13 );
3365
3366     # Daily Tests
3367     t::lib::Mocks::mock_preference( 'finesCalendar', 'ignoreCalendar' );
3368     my $issue =
3369       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3370     my $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3371     is( $accountline->amount+0, 7,
3372 "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar"
3373     );
3374     $accountline->delete();
3375     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3376     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3377     is( $accountline->amount+0, 6,
3378 "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar, for renewal"
3379     );
3380     $accountline->delete();
3381     $issue->delete();
3382
3383     t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
3384     $issue =
3385       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3386     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3387     is( $accountline->amount+0, 7,
3388 "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed"
3389     );
3390     $accountline->delete();
3391     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3392     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3393     is( $accountline->amount+0, 6,
3394 "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed, for renewal"
3395     );
3396     $accountline->delete();
3397     $issue->delete();
3398
3399     my $calendar = C4::Calendar->new( branchcode => $library->id );
3400     # DateTime 1..7 (Mon..Sun), C4::Calender 0..6 (Sun..Sat)
3401     my $closed_day =
3402         ( $dt_from->day_of_week == 6 ) ? 0
3403       : ( $dt_from->day_of_week == 7 ) ? 1
3404       :                                  $dt_from->day_of_week + 1;
3405     my $closed_day_name = $dt_from->clone->add(days => 1)->day_name;
3406     $calendar->insert_week_day_holiday(
3407         weekday     => $closed_day,
3408         title       => 'Test holiday',
3409         description => 'Test holiday'
3410     );
3411     $issue =
3412       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3413     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3414     is( $accountline->amount+0, 6,
3415 "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $closed_day_name"
3416     );
3417     $accountline->delete();
3418     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3419     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3420     is( $accountline->amount+0, 5,
3421 "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $closed_day_name, for renewal"
3422     );
3423     $accountline->delete();
3424     $issue->delete();
3425
3426     $itemtype->rentalcharge(2)->store;
3427     is( $itemtype->rentalcharge+0, 2,
3428         'Rental charge updated and retreived correctly' );
3429     $issue =
3430       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3431     my $accountlines =
3432       Koha::Account::Lines->search( { itemnumber => $item->id } );
3433     is( $accountlines->count, '2',
3434         "Fixed charge and accrued charge recorded distinctly" );
3435     $accountlines->delete();
3436     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3437     $accountlines = Koha::Account::Lines->search( { itemnumber => $item->id } );
3438     is( $accountlines->count, '2',
3439         "Fixed charge and accrued charge recorded distinctly, for renewal" );
3440     $accountlines->delete();
3441     $issue->delete();
3442     $itemtype->rentalcharge(0)->store;
3443     is( $itemtype->rentalcharge+0, 0,
3444         'Rental charge reset and retreived correctly' );
3445
3446     # Hourly
3447     my $issuingrule = Koha::IssuingRules->get_effective_issuing_rule(
3448         {
3449             categorycode => $patron->categorycode,
3450             itemtype     => $itemtype->id,
3451             branchcode   => $library->id
3452         }
3453     );
3454     $issuingrule->lengthunit('hours')->store();
3455     is( $issuingrule->lengthunit, 'hours',
3456         'Issuingrule updated and retrieved correctly' );
3457
3458     $itemtype->rentalcharge_hourly('0.25')->store();
3459     is( $itemtype->rentalcharge_hourly,
3460         '0.25', 'Hourly rental charge stored and retreived correctly' );
3461
3462     $dt_to       = dt_from_string()->add( hours => 168 );
3463     $dt_to_renew = dt_from_string()->add( hours => 312 );
3464
3465     t::lib::Mocks::mock_preference( 'finesCalendar', 'ignoreCalendar' );
3466     $issue =
3467       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3468     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3469     is( $accountline->amount + 0, 42,
3470         "Hourly rental charge calculated correctly with finesCalendar = ignoreCalendar (168h * 0.25u)" );
3471     $accountline->delete();
3472     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3473     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3474     is( $accountline->amount + 0, 36,
3475         "Hourly rental charge calculated correctly with finesCalendar = ignoreCalendar, for renewal (312h - 168h * 0.25u)" );
3476     $accountline->delete();
3477     $issue->delete();
3478
3479     t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
3480     $issue =
3481       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3482     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3483     is( $accountline->amount + 0, 36,
3484         "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $closed_day_name (168h - 24h * 0.25u)" );
3485     $accountline->delete();
3486     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3487     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3488     is( $accountline->amount + 0, 30,
3489         "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $closed_day_name, for renewal (312h - 168h - 24h * 0.25u" );
3490     $accountline->delete();
3491     $issue->delete();
3492
3493     $calendar->delete_holiday( weekday => $closed_day );
3494     $issue =
3495       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3496     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3497     is( $accountline->amount + 0, 42,
3498         "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed (168h - 0h * 0.25u" );
3499     $accountline->delete();
3500     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3501     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3502     is( $accountline->amount + 0, 36,
3503         "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed, for renewal (312h - 168h - 0h * 0.25u)" );
3504     $accountline->delete();
3505     $issue->delete();
3506     $issuingrule->lengthunit('days')->store();
3507     Time::Fake->reset;
3508 };
3509
3510 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
3511     plan tests => 2;
3512
3513     t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
3514     t::lib::Mocks::mock_preference('item-level_itypes', 1);
3515
3516     my $library =
3517       $builder->build_object( { class => 'Koha::Libraries' } )->store;
3518     my $patron = $builder->build_object(
3519         {
3520             class => 'Koha::Patrons',
3521             value => { categorycode => $patron_category->{categorycode} }
3522         }
3523     )->store;
3524
3525     my $itemtype = $builder->build_object(
3526         {
3527             class => 'Koha::ItemTypes',
3528             value => {
3529                 notforloan             => 0,
3530                 rentalcharge           => 0,
3531                 rentalcharge_daily => 0
3532             }
3533         }
3534     );
3535
3536     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
3537     my $item = $builder->build_object(
3538         {
3539             class => 'Koha::Items',
3540             value  => {
3541                 homebranch    => $library->id,
3542                 holdingbranch => $library->id,
3543                 notforloan    => 0,
3544                 itemlost      => 0,
3545                 withdrawn     => 0,
3546                 itype         => $itemtype->id,
3547                 biblionumber  => $biblioitem->{biblionumber},
3548                 biblioitemnumber => $biblioitem->{biblioitemnumber},
3549             }
3550         }
3551     )->store;
3552
3553     my ( $issuingimpossible, $needsconfirmation );
3554     my $dt_from = dt_from_string();
3555     my $dt_due = dt_from_string()->add( days => 3 );
3556
3557     $itemtype->rentalcharge(1)->store;
3558     ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3559     is_deeply( $needsconfirmation, { RENTALCHARGE => '1.00' }, 'Item needs rentalcharge confirmation to be issued' );
3560     $itemtype->rentalcharge('0')->store;
3561     $itemtype->rentalcharge_daily(1)->store;
3562     ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3563     is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
3564     $itemtype->rentalcharge_daily('0')->store;
3565 };
3566
3567 subtest "Test Backdating of Returns" => sub {
3568     plan tests => 2;
3569
3570     my $branch = $library2->{branchcode};
3571     my $biblio = $builder->build_sample_biblio();
3572     my $item = $builder->build_sample_item(
3573         {
3574             biblionumber     => $biblio->biblionumber,
3575             library          => $branch,
3576             itype            => $itemtype,
3577         }
3578     );
3579
3580     my %a_borrower_data = (
3581         firstname =>  'Kyle',
3582         surname => 'Hall',
3583         categorycode => $patron_category->{categorycode},
3584         branchcode => $branch,
3585     );
3586     my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
3587     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
3588
3589     my $due_date = dt_from_string;
3590     my $issue = AddIssue( $borrower, $item->barcode, $due_date );
3591     UpdateFine(
3592         {
3593             issue_id          => $issue->id(),
3594             itemnumber        => $item->itemnumber,
3595             borrowernumber    => $borrowernumber,
3596             amount            => .25,
3597             amountoutstanding => .25,
3598             type              => q{}
3599         }
3600     );
3601
3602
3603     my ( undef, $message ) = AddReturn( $item->barcode, $branch, undef, $due_date );
3604
3605     my $accountline = Koha::Account::Lines->find( { issue_id => $issue->id } );
3606     is( $accountline->amountoutstanding+0, 0, 'Fee amount outstanding was reduced to 0' );
3607     is( $accountline->amount+0, 0, 'Fee amount was reduced to 0' );
3608 };
3609
3610 $schema->storage->txn_rollback;
3611 C4::Context->clear_syspref_cache();
3612 $cache->clear_from_cache('single_holidays');