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