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