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