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