Bug 27993: Add unit tests
[koha.git] / t / db_dependent / Circulation.t
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19 use utf8;
20
21 use Test::More tests => 53;
22 use Test::Exception;
23 use Test::MockModule;
24 use Test::Deep qw( cmp_deeply );
25 use Test::Warn;
26
27 use Data::Dumper;
28 use DateTime;
29 use Time::Fake;
30 use POSIX qw( floor );
31 use t::lib::Mocks;
32 use t::lib::TestBuilder;
33
34 use C4::Accounts;
35 use C4::Calendar;
36 use C4::Circulation;
37 use C4::Biblio;
38 use C4::Items;
39 use C4::Log;
40 use C4::Reserves;
41 use C4::Overdues qw(UpdateFine CalcFine);
42 use Koha::DateUtils;
43 use Koha::Database;
44 use Koha::Items;
45 use Koha::Item::Transfers;
46 use Koha::Checkouts;
47 use Koha::Patrons;
48 use Koha::Holds;
49 use Koha::CirculationRules;
50 use Koha::Subscriptions;
51 use Koha::Account::Lines;
52 use Koha::Account::Offsets;
53 use Koha::ActionLogs;
54
55 sub set_userenv {
56     my ( $library ) = @_;
57     t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
58 }
59
60 sub str {
61     my ( $error, $question, $alert ) = @_;
62     my $s;
63     $s  = %$error    ? ' (error: '    . join( ' ', keys %$error    ) . ')' : '';
64     $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
65     $s .= %$alert    ? ' (alert: '    . join( ' ', keys %$alert    ) . ')' : '';
66     return $s;
67 }
68
69 sub test_debarment_on_checkout {
70     my ($params) = @_;
71     my $item     = $params->{item};
72     my $library  = $params->{library};
73     my $patron   = $params->{patron};
74     my $due_date = $params->{due_date} || dt_from_string;
75     my $return_date = $params->{return_date} || dt_from_string;
76     my $expected_expiration_date = $params->{expiration_date};
77
78     $expected_expiration_date = output_pref(
79         {
80             dt         => $expected_expiration_date,
81             dateformat => 'sql',
82             dateonly   => 1,
83         }
84     );
85     my @caller      = caller;
86     my $line_number = $caller[2];
87     AddIssue( $patron, $item->barcode, $due_date );
88
89     my ( undef, $message ) = AddReturn( $item->barcode, $library->{branchcode}, undef, $return_date );
90     is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' )
91         or diag('AddReturn returned message ' . Dumper $message );
92     my $debarments = Koha::Patron::Debarments::GetDebarments(
93         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
94     is( scalar(@$debarments), 1, 'Test at line ' . $line_number );
95
96     is( $debarments->[0]->{expiration},
97         $expected_expiration_date, 'Test at line ' . $line_number );
98     Koha::Patron::Debarments::DelUniqueDebarment(
99         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
100 };
101
102 my $schema = Koha::Database->schema;
103 $schema->storage->txn_begin;
104 my $builder = t::lib::TestBuilder->new;
105 my $dbh = C4::Context->dbh;
106
107 # Prevent random failures by mocking ->now
108 my $now_value       = dt_from_string;
109 my $mocked_datetime = Test::MockModule->new('DateTime');
110 $mocked_datetime->mock( 'now', sub { return $now_value->clone; } );
111
112 my $cache = Koha::Caches->get_instance();
113 $dbh->do(q|DELETE FROM special_holidays|);
114 $dbh->do(q|DELETE FROM repeatable_holidays|);
115 my $branches = Koha::Libraries->search();
116 for my $branch ( $branches->next ) {
117     my $key = $branch->branchcode . "_holidays";
118     $cache->clear_from_cache($key);
119 }
120
121 # Start with a clean slate
122 $dbh->do('DELETE FROM issues');
123 $dbh->do('DELETE FROM borrowers');
124
125 # Disable recording of the staff who checked out an item until we're ready for it
126 t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 0);
127
128 my $module = Test::MockModule->new('C4::Context');
129
130 my $library = $builder->build({
131     source => 'Branch',
132 });
133 my $library2 = $builder->build({
134     source => 'Branch',
135 });
136 my $itemtype = $builder->build(
137     {
138         source => 'Itemtype',
139         value  => {
140             notforloan          => undef,
141             rentalcharge        => 0,
142             rentalcharge_daily => 0,
143             defaultreplacecost  => undef,
144             processfee          => undef
145         }
146     }
147 )->{itemtype};
148 my $patron_category = $builder->build(
149     {
150         source => 'Category',
151         value  => {
152             category_type                 => 'P',
153             enrolmentfee                  => 0,
154             BlockExpiredPatronOpacActions => -1, # Pick the pref value
155         }
156     }
157 );
158
159 my $CircControl = C4::Context->preference('CircControl');
160 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
161
162 my $item = {
163     homebranch => $library2->{branchcode},
164     holdingbranch => $library2->{branchcode}
165 };
166
167 my $borrower = {
168     branchcode => $library2->{branchcode}
169 };
170
171 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
172
173 # No userenv, PickupLibrary
174 t::lib::Mocks::mock_preference('IndependentBranches', '0');
175 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
176 is(
177     C4::Context->preference('CircControl'),
178     'PickupLibrary',
179     'CircControl changed to PickupLibrary'
180 );
181 is(
182     C4::Circulation::_GetCircControlBranch($item, $borrower),
183     $item->{$HomeOrHoldingBranch},
184     '_GetCircControlBranch returned item branch (no userenv defined)'
185 );
186
187 # No userenv, PatronLibrary
188 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
189 is(
190     C4::Context->preference('CircControl'),
191     'PatronLibrary',
192     'CircControl changed to PatronLibrary'
193 );
194 is(
195     C4::Circulation::_GetCircControlBranch($item, $borrower),
196     $borrower->{branchcode},
197     '_GetCircControlBranch returned borrower branch'
198 );
199
200 # No userenv, ItemHomeLibrary
201 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
202 is(
203     C4::Context->preference('CircControl'),
204     'ItemHomeLibrary',
205     'CircControl changed to ItemHomeLibrary'
206 );
207 is(
208     $item->{$HomeOrHoldingBranch},
209     C4::Circulation::_GetCircControlBranch($item, $borrower),
210     '_GetCircControlBranch returned item branch'
211 );
212
213 # Now, set a userenv
214 t::lib::Mocks::mock_userenv({ branchcode => $library2->{branchcode} });
215 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
216
217 # Userenv set, PickupLibrary
218 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
219 is(
220     C4::Context->preference('CircControl'),
221     'PickupLibrary',
222     'CircControl changed to PickupLibrary'
223 );
224 is(
225     C4::Circulation::_GetCircControlBranch($item, $borrower),
226     $library2->{branchcode},
227     '_GetCircControlBranch returned current branch'
228 );
229
230 # Userenv set, PatronLibrary
231 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
232 is(
233     C4::Context->preference('CircControl'),
234     'PatronLibrary',
235     'CircControl changed to PatronLibrary'
236 );
237 is(
238     C4::Circulation::_GetCircControlBranch($item, $borrower),
239     $borrower->{branchcode},
240     '_GetCircControlBranch returned borrower branch'
241 );
242
243 # Userenv set, ItemHomeLibrary
244 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
245 is(
246     C4::Context->preference('CircControl'),
247     'ItemHomeLibrary',
248     'CircControl changed to ItemHomeLibrary'
249 );
250 is(
251     C4::Circulation::_GetCircControlBranch($item, $borrower),
252     $item->{$HomeOrHoldingBranch},
253     '_GetCircControlBranch returned item branch'
254 );
255
256 # Reset initial configuration
257 t::lib::Mocks::mock_preference('CircControl', $CircControl);
258 is(
259     C4::Context->preference('CircControl'),
260     $CircControl,
261     'CircControl reset to its initial value'
262 );
263
264 # Set a simple circ policy
265 $dbh->do('DELETE FROM circulation_rules');
266 Koha::CirculationRules->set_rules(
267     {
268         categorycode => undef,
269         branchcode   => undef,
270         itemtype     => undef,
271         rules        => {
272             reservesallowed => 25,
273             issuelength     => 14,
274             lengthunit      => 'days',
275             renewalsallowed => 1,
276             renewalperiod   => 7,
277             norenewalbefore => undef,
278             auto_renew      => 0,
279             fine            => .10,
280             chargeperiod    => 1,
281         }
282     }
283 );
284
285 subtest "GetIssuingCharges tests" => sub {
286     plan tests => 4;
287     my $branch_discount = $builder->build_object({ class => 'Koha::Libraries' });
288     my $branch_no_discount = $builder->build_object({ class => 'Koha::Libraries' });
289     Koha::CirculationRules->set_rule(
290         {
291             categorycode => undef,
292             branchcode   => $branch_discount->branchcode,
293             itemtype     => undef,
294             rule_name    => 'rentaldiscount',
295             rule_value   => 15
296         }
297     );
298     my $itype_charge = $builder->build_object({
299         class => 'Koha::ItemTypes',
300         value => {
301             rentalcharge => 10
302         }
303     });
304     my $itype_no_charge = $builder->build_object({
305         class => 'Koha::ItemTypes',
306         value => {
307             rentalcharge => 0
308         }
309     });
310     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
311     my $item_1 = $builder->build_sample_item({ itype => $itype_charge->itemtype });
312     my $item_2 = $builder->build_sample_item({ itype => $itype_no_charge->itemtype });
313
314     t::lib::Mocks::mock_userenv({ branchcode => $branch_no_discount->branchcode });
315     # For now the sub always uses the env branch, this should follow CircControl instead
316     my ($charge, $itemtype) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber);
317     is( $charge + 0, 10.00, "Charge fetched correctly when no discount exists");
318     ($charge, $itemtype) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber);
319     is( $charge + 0, 0.00, "Charge fetched correctly when no discount exists and no charge");
320
321     t::lib::Mocks::mock_userenv({ branchcode => $branch_discount->branchcode });
322     # For now the sub always uses the env branch, this should follow CircControl instead
323     ($charge, $itemtype) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber);
324     is( $charge + 0, 8.50, "Charge fetched correctly when discount exists");
325     ($charge, $itemtype) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber);
326     is( $charge + 0, 0.00, "Charge fetched correctly when discount exists and no charge");
327
328 };
329
330 my ( $reused_itemnumber_1, $reused_itemnumber_2 );
331 subtest "CanBookBeRenewed tests" => sub {
332     plan tests => 95;
333
334     C4::Context->set_preference('ItemsDeniedRenewal','');
335     # Generate test biblio
336     my $biblio = $builder->build_sample_biblio();
337
338     my $branch = $library2->{branchcode};
339
340     my $item_1 = $builder->build_sample_item(
341         {
342             biblionumber     => $biblio->biblionumber,
343             library          => $branch,
344             replacementprice => 12.00,
345             itype            => $itemtype
346         }
347     );
348     $reused_itemnumber_1 = $item_1->itemnumber;
349
350     my $item_2 = $builder->build_sample_item(
351         {
352             biblionumber     => $biblio->biblionumber,
353             library          => $branch,
354             replacementprice => 23.00,
355             itype            => $itemtype
356         }
357     );
358     $reused_itemnumber_2 = $item_2->itemnumber;
359
360     my $item_3 = $builder->build_sample_item(
361         {
362             biblionumber     => $biblio->biblionumber,
363             library          => $branch,
364             replacementprice => 23.00,
365             itype            => $itemtype
366         }
367     );
368
369     # Create borrowers
370     my %renewing_borrower_data = (
371         firstname =>  'John',
372         surname => 'Renewal',
373         categorycode => $patron_category->{categorycode},
374         branchcode => $branch,
375     );
376
377     my %reserving_borrower_data = (
378         firstname =>  'Katrin',
379         surname => 'Reservation',
380         categorycode => $patron_category->{categorycode},
381         branchcode => $branch,
382     );
383
384     my %hold_waiting_borrower_data = (
385         firstname =>  'Kyle',
386         surname => 'Reservation',
387         categorycode => $patron_category->{categorycode},
388         branchcode => $branch,
389     );
390
391     my %restricted_borrower_data = (
392         firstname =>  'Alice',
393         surname => 'Reservation',
394         categorycode => $patron_category->{categorycode},
395         debarred => '3228-01-01',
396         branchcode => $branch,
397     );
398
399     my %expired_borrower_data = (
400         firstname =>  'Ça',
401         surname => 'Glisse',
402         categorycode => $patron_category->{categorycode},
403         branchcode => $branch,
404         dateexpiry => dt_from_string->subtract( months => 1 ),
405     );
406
407     my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
408     my $reserving_borrowernumber = Koha::Patron->new(\%reserving_borrower_data)->store->borrowernumber;
409     my $hold_waiting_borrowernumber = Koha::Patron->new(\%hold_waiting_borrower_data)->store->borrowernumber;
410     my $restricted_borrowernumber = Koha::Patron->new(\%restricted_borrower_data)->store->borrowernumber;
411     my $expired_borrowernumber = Koha::Patron->new(\%expired_borrower_data)->store->borrowernumber;
412
413     my $renewing_borrower_obj = Koha::Patrons->find( $renewing_borrowernumber );
414     my $renewing_borrower = $renewing_borrower_obj->unblessed;
415     my $restricted_borrower = Koha::Patrons->find( $restricted_borrowernumber )->unblessed;
416     my $expired_borrower = Koha::Patrons->find( $expired_borrowernumber )->unblessed;
417
418     my $bibitems       = '';
419     my $priority       = '1';
420     my $resdate        = undef;
421     my $expdate        = undef;
422     my $notes          = '';
423     my $checkitem      = undef;
424     my $found          = undef;
425
426     my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
427     my $datedue = dt_from_string( $issue->date_due() );
428     is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
429
430     my $issue2 = AddIssue( $renewing_borrower, $item_2->barcode);
431     $datedue = dt_from_string( $issue->date_due() );
432     is (defined $issue2, 1, "Item 2 checked out, due date: " . $issue2->date_due());
433
434
435     my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $item_1->itemnumber } )->borrowernumber;
436     is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
437
438     my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
439     is( $renewokay, 1, 'Can renew, no holds for this title or item');
440
441
442     # Biblio-level hold, renewal test
443     AddReserve(
444         {
445             branchcode       => $branch,
446             borrowernumber   => $reserving_borrowernumber,
447             biblionumber     => $biblio->biblionumber,
448             priority         => $priority,
449             reservation_date => $resdate,
450             expiration_date  => $expdate,
451             notes            => $notes,
452             itemnumber       => $checkitem,
453             found            => $found,
454         }
455     );
456
457     # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
458     Koha::CirculationRules->set_rule(
459         {
460             categorycode => undef,
461             branchcode   => undef,
462             itemtype     => undef,
463             rule_name    => 'onshelfholds',
464             rule_value   => '1',
465         }
466     );
467     Koha::CirculationRules->set_rule(
468         {
469             categorycode => undef,
470             branchcode   => undef,
471             itemtype     => undef,
472             rule_name    => 'renewalsallowed',
473             rule_value   => '5',
474         }
475     );
476     t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
477     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
478     is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
479     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
480     is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
481
482     # Now let's add an item level hold, we should no longer be able to renew the item
483     my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
484         {
485             borrowernumber => $hold_waiting_borrowernumber,
486             biblionumber   => $biblio->biblionumber,
487             itemnumber     => $item_1->itemnumber,
488             branchcode     => $branch,
489             priority       => 3,
490         }
491     );
492     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
493     is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
494     $hold->delete();
495
496     # 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
497     # be able to renew these items
498     $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
499         {
500             borrowernumber => $hold_waiting_borrowernumber,
501             biblionumber   => $biblio->biblionumber,
502             itemnumber     => $item_3->itemnumber,
503             branchcode     => $branch,
504             priority       => 0,
505             found          => 'W'
506         }
507     );
508     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
509     is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
510     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
511     is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
512     t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
513
514     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
515     is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
516     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
517
518     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
519     is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
520     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
521
522     my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
523     my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber )->unblessed;
524     AddIssue($reserving_borrower, $item_3->barcode);
525     my $reserve = $dbh->selectrow_hashref(
526         'SELECT * FROM old_reserves WHERE reserve_id = ?',
527         { Slice => {} },
528         $reserveid
529     );
530     is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
531
532     # Item-level hold, renewal test
533     AddReserve(
534         {
535             branchcode       => $branch,
536             borrowernumber   => $reserving_borrowernumber,
537             biblionumber     => $biblio->biblionumber,
538             priority         => $priority,
539             reservation_date => $resdate,
540             expiration_date  => $expdate,
541             notes            => $notes,
542             itemnumber       => $item_1->itemnumber,
543             found            => $found,
544         }
545     );
546
547     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
548     is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
549     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
550
551     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber, 1);
552     is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
553
554     # Items can't fill hold for reasons
555     $item_1->notforloan(1)->store;
556     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
557     is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
558     $item_1->set({notforloan => 0, itype => $itemtype })->store;
559
560     # FIXME: Add more for itemtype not for loan etc.
561
562     # Restricted users cannot renew when RestrictionBlockRenewing is enabled
563     my $item_5 = $builder->build_sample_item(
564         {
565             biblionumber     => $biblio->biblionumber,
566             library          => $branch,
567             replacementprice => 23.00,
568             itype            => $itemtype,
569         }
570     );
571     my $datedue5 = AddIssue($restricted_borrower, $item_5->barcode);
572     is (defined $datedue5, 1, "Item with date due checked out, due date: $datedue5");
573
574     t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
575     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
576     is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
577     ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrowernumber, $item_5->itemnumber);
578     is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
579     is( $error, 'restriction', "Correct error returned");
580
581     # Users cannot renew an overdue item
582     my $item_6 = $builder->build_sample_item(
583         {
584             biblionumber     => $biblio->biblionumber,
585             library          => $branch,
586             replacementprice => 23.00,
587             itype            => $itemtype,
588         }
589     );
590
591     my $item_7 = $builder->build_sample_item(
592         {
593             biblionumber     => $biblio->biblionumber,
594             library          => $branch,
595             replacementprice => 23.00,
596             itype            => $itemtype,
597         }
598     );
599
600     my $datedue6 = AddIssue( $renewing_borrower, $item_6->barcode);
601     is (defined $datedue6, 1, "Item 2 checked out, due date: ".$datedue6->date_due);
602
603     my $now = dt_from_string();
604     my $five_weeks = DateTime::Duration->new(weeks => 5);
605     my $five_weeks_ago = $now - $five_weeks;
606     t::lib::Mocks::mock_preference('finesMode', 'production');
607
608     my $passeddatedue1 = AddIssue($renewing_borrower, $item_7->barcode, $five_weeks_ago);
609     is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: " . $passeddatedue1->date_due);
610
611     my ( $fine ) = CalcFine( $item_7->unblessed, $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
612     C4::Overdues::UpdateFine(
613         {
614             issue_id       => $passeddatedue1->id(),
615             itemnumber     => $item_7->itemnumber,
616             borrowernumber => $renewing_borrower->{borrowernumber},
617             amount         => $fine,
618             due            => Koha::DateUtils::output_pref($five_weeks_ago)
619         }
620     );
621
622     t::lib::Mocks::mock_preference('RenewalLog', 0);
623     my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
624     my %params_renewal = (
625         timestamp => { -like => $date . "%" },
626         module => "CIRCULATION",
627         action => "RENEWAL",
628     );
629     my %params_issue = (
630         timestamp => { -like => $date . "%" },
631         module => "CIRCULATION",
632         action => "ISSUE"
633     );
634     my $old_log_size = Koha::ActionLogs->count( \%params_renewal );
635     my $dt = dt_from_string();
636     Time::Fake->offset( $dt->epoch );
637     my $datedue1 = AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
638     my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
639     is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
640     isnt (DateTime->compare($datedue1, $dt), 0, "AddRenewal returned a good duedate");
641     Time::Fake->reset;
642
643     t::lib::Mocks::mock_preference('RenewalLog', 1);
644     $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
645     $old_log_size = Koha::ActionLogs->count( \%params_renewal );
646     AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
647     $new_log_size = Koha::ActionLogs->count( \%params_renewal );
648     is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
649
650     my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
651     is( $fines->count, 2, 'AddRenewal left both fines' );
652     isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
653     isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
654     $fines->delete();
655
656     t::lib::Mocks::mock_preference('OverduesBlockRenewing','allow');
657     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
658     is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
659     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
660     is( $renewokay, 1, '(Bug 8236), Can renew, this item is overdue but not pref does not block');
661
662     t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
663     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
664     is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is not overdue but patron has overdues');
665     is( $error, 'overdue', "Correct error returned");
666     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
667     is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue so patron has overdues');
668     is( $error, 'overdue', "Correct error returned");
669
670     t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
671     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
672     is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
673     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
674     is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
675     is( $error, 'overdue', "Correct error returned");
676
677
678     my $old_issue_log_size = Koha::ActionLogs->count( \%params_issue );
679     my $old_renew_log_size = Koha::ActionLogs->count( \%params_renewal );
680     AddIssue( $renewing_borrower,$item_7->barcode,Koha::DateUtils::output_pref({str=>$datedue6->date_due, dateformat =>'iso'}),0,$date, 0, undef );
681     $new_log_size = Koha::ActionLogs->count( \%params_renewal );
682     is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
683     $new_log_size = Koha::ActionLogs->count( \%params_issue );
684     is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
685
686     $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
687     $fines->delete();
688
689     $hold = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next;
690     $hold->cancel;
691
692     # Bug 14101
693     # Test automatic renewal before value for "norenewalbefore" in policy is set
694     # In this case automatic renewal is not permitted prior to due date
695     my $item_4 = $builder->build_sample_item(
696         {
697             biblionumber     => $biblio->biblionumber,
698             library          => $branch,
699             replacementprice => 16.00,
700             itype            => $itemtype,
701         }
702     );
703
704     $issue = AddIssue( $renewing_borrower, $item_4->barcode, undef, undef, undef, undef, { auto_renew => 1 } );
705     ( $renewokay, $error ) =
706       CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
707     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
708     is( $error, 'auto_too_soon',
709         'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
710     AddReserve(
711         {
712             branchcode       => $branch,
713             borrowernumber   => $reserving_borrowernumber,
714             biblionumber     => $biblio->biblionumber,
715             itemnumber       => $bibitems,
716             priority         => $priority,
717             reservation_date => $resdate,
718             expiration_date  => $expdate,
719             notes            => $notes,
720             title            => 'a title',
721             itemnumber       => $item_4->itemnumber,
722             found            => $found
723         }
724     );
725     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
726     is( $renewokay, 0, 'Still should not be able to renew' );
727     is( $error, 'on_reserve', 'returned code is on_reserve, reserve checked when not checking for cron' );
728     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, undef, 1 );
729     is( $renewokay, 0, 'Still should not be able to renew' );
730     is( $error, 'auto_too_soon', 'returned code is auto_too_soon, reserve not checked when checking for cron' );
731     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
732     is( $renewokay, 0, 'Still should not be able to renew' );
733     is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
734     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1, 1 );
735     is( $renewokay, 0, 'Still should not be able to renew' );
736     is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
737     $dbh->do('UPDATE circulation_rules SET rule_value = 0 where rule_name = "norenewalbefore"');
738     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
739     is( $renewokay, 0, 'Still should not be able to renew' );
740     is( $error, 'on_reserve', 'returned code is on_reserve, auto_renew only happens if not on reserve' );
741     ModReserveCancelAll($item_4->itemnumber, $reserving_borrowernumber);
742
743
744
745     $renewing_borrower_obj->autorenew_checkouts(0)->store;
746     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
747     is( $renewokay, 1, 'No renewal before is undef, but patron opted out of auto_renewal' );
748     $renewing_borrower_obj->autorenew_checkouts(1)->store;
749
750
751     # Bug 7413
752     # Test premature manual renewal
753     Koha::CirculationRules->set_rule(
754         {
755             categorycode => undef,
756             branchcode   => undef,
757             itemtype     => undef,
758             rule_name    => 'norenewalbefore',
759             rule_value   => '7',
760         }
761     );
762
763     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
764     is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
765     is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
766
767     # Bug 14395
768     # Test 'exact time' setting for syspref NoRenewalBeforePrecision
769     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
770     is(
771         GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
772         $datedue->clone->add( days => -7 ),
773         'Bug 14395: Renewals permitted 7 days before due date, as expected'
774     );
775
776     # Bug 14395
777     # Test 'date' setting for syspref NoRenewalBeforePrecision
778     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
779     is(
780         GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
781         $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
782         'Bug 14395: Renewals permitted 7 days before due date, as expected'
783     );
784
785     # Bug 14101
786     # Test premature automatic renewal
787     ( $renewokay, $error ) =
788       CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
789     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
790     is( $error, 'auto_too_soon',
791         'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
792     );
793
794     $renewing_borrower_obj->autorenew_checkouts(0)->store;
795     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
796     is( $renewokay, 0, 'No renewal before is 7, patron opted out of auto_renewal still cannot renew early' );
797     is( $error, 'too_soon', 'Error is too_soon, no auto' );
798     $renewing_borrower_obj->autorenew_checkouts(1)->store;
799
800     # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
801     # and test automatic renewal again
802     $dbh->do(q{UPDATE circulation_rules SET rule_value = '0' WHERE rule_name = 'norenewalbefore'});
803     ( $renewokay, $error ) =
804       CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
805     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
806     is( $error, 'auto_too_soon',
807         'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
808     );
809
810     $renewing_borrower_obj->autorenew_checkouts(0)->store;
811     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
812     is( $renewokay, 0, 'No renewal before is 0, patron opted out of auto_renewal still cannot renew early' );
813     is( $error, 'too_soon', 'Error is too_soon, no auto' );
814     $renewing_borrower_obj->autorenew_checkouts(1)->store;
815
816     # Change policy so that loans can be renewed 99 days prior to the due date
817     # and test automatic renewal again
818     $dbh->do(q{UPDATE circulation_rules SET rule_value = '99' WHERE rule_name = 'norenewalbefore'});
819     ( $renewokay, $error ) =
820       CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
821     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
822     is( $error, 'auto_renew',
823         'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
824     );
825
826     $renewing_borrower_obj->autorenew_checkouts(0)->store;
827     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
828     is( $renewokay, 1, 'No renewal before is 99, patron opted out of auto_renewal so can renew' );
829     $renewing_borrower_obj->autorenew_checkouts(1)->store;
830
831     subtest "too_late_renewal / no_auto_renewal_after" => sub {
832         plan tests => 14;
833         my $item_to_auto_renew = $builder->build_sample_item(
834             {
835                 biblionumber => $biblio->biblionumber,
836                 library      => $branch,
837             }
838         );
839
840         my $ten_days_before = dt_from_string->add( days => -10 );
841         my $ten_days_ahead  = dt_from_string->add( days => 10 );
842         AddIssue( $renewing_borrower, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
843
844         Koha::CirculationRules->set_rules(
845             {
846                 categorycode => undef,
847                 branchcode   => undef,
848                 itemtype     => undef,
849                 rules        => {
850                     norenewalbefore       => '7',
851                     no_auto_renewal_after => '9',
852                 }
853             }
854         );
855         ( $renewokay, $error ) =
856           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
857         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
858         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
859
860         Koha::CirculationRules->set_rules(
861             {
862                 categorycode => undef,
863                 branchcode   => undef,
864                 itemtype     => undef,
865                 rules        => {
866                     norenewalbefore       => '7',
867                     no_auto_renewal_after => '10',
868                 }
869             }
870         );
871         ( $renewokay, $error ) =
872           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
873         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
874         is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
875
876         Koha::CirculationRules->set_rules(
877             {
878                 categorycode => undef,
879                 branchcode   => undef,
880                 itemtype     => undef,
881                 rules        => {
882                     norenewalbefore       => '7',
883                     no_auto_renewal_after => '11',
884                 }
885             }
886         );
887         ( $renewokay, $error ) =
888           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
889         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
890         is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
891
892         Koha::CirculationRules->set_rules(
893             {
894                 categorycode => undef,
895                 branchcode   => undef,
896                 itemtype     => undef,
897                 rules        => {
898                     norenewalbefore       => '10',
899                     no_auto_renewal_after => '11',
900                 }
901             }
902         );
903         ( $renewokay, $error ) =
904           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
905         is( $renewokay, 0,            'Do not renew, renewal is automatic' );
906         is( $error,     'auto_renew', 'Cannot renew, renew is automatic' );
907
908         Koha::CirculationRules->set_rules(
909             {
910                 categorycode => undef,
911                 branchcode   => undef,
912                 itemtype     => undef,
913                 rules        => {
914                     norenewalbefore       => '10',
915                     no_auto_renewal_after => undef,
916                     no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
917                 }
918             }
919         );
920         ( $renewokay, $error ) =
921           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
922         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
923         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
924
925         Koha::CirculationRules->set_rules(
926             {
927                 categorycode => undef,
928                 branchcode   => undef,
929                 itemtype     => undef,
930                 rules        => {
931                     norenewalbefore       => '7',
932                     no_auto_renewal_after => '15',
933                     no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
934                 }
935             }
936         );
937         ( $renewokay, $error ) =
938           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
939         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
940         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
941
942         Koha::CirculationRules->set_rules(
943             {
944                 categorycode => undef,
945                 branchcode   => undef,
946                 itemtype     => undef,
947                 rules        => {
948                     norenewalbefore       => '10',
949                     no_auto_renewal_after => undef,
950                     no_auto_renewal_after_hard_limit => dt_from_string->add( days => 1 ),
951                 }
952             }
953         );
954         ( $renewokay, $error ) =
955           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
956         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
957         is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
958     };
959
960     subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew & OPACFineNoRenewalsIncludeCredit" => sub {
961         plan tests => 10;
962         my $item_to_auto_renew = $builder->build_sample_item(
963             {
964                 biblionumber => $biblio->biblionumber,
965                 library      => $branch,
966             }
967         );
968
969         my $ten_days_before = dt_from_string->add( days => -10 );
970         my $ten_days_ahead = dt_from_string->add( days => 10 );
971         AddIssue( $renewing_borrower, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
972
973         Koha::CirculationRules->set_rules(
974             {
975                 categorycode => undef,
976                 branchcode   => undef,
977                 itemtype     => undef,
978                 rules        => {
979                     norenewalbefore       => '10',
980                     no_auto_renewal_after => '11',
981                 }
982             }
983         );
984         C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
985         C4::Context->set_preference('OPACFineNoRenewals','10');
986         C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
987         my $fines_amount = 5;
988         my $account = Koha::Account->new({patron_id => $renewing_borrowernumber});
989         $account->add_debit(
990             {
991                 amount      => $fines_amount,
992                 interface   => 'test',
993                 type        => 'OVERDUE',
994                 item_id     => $item_to_auto_renew->itemnumber,
995                 description => "Some fines"
996             }
997         )->status('RETURNED')->store;
998         ( $renewokay, $error ) =
999           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1000         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1001         is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
1002
1003         $account->add_debit(
1004             {
1005                 amount      => $fines_amount,
1006                 interface   => 'test',
1007                 type        => 'OVERDUE',
1008                 item_id     => $item_to_auto_renew->itemnumber,
1009                 description => "Some fines"
1010             }
1011         )->status('RETURNED')->store;
1012         ( $renewokay, $error ) =
1013           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1014         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1015         is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
1016
1017         $account->add_debit(
1018             {
1019                 amount      => $fines_amount,
1020                 interface   => 'test',
1021                 type        => 'OVERDUE',
1022                 item_id     => $item_to_auto_renew->itemnumber,
1023                 description => "Some fines"
1024             }
1025         )->status('RETURNED')->store;
1026         ( $renewokay, $error ) =
1027           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1028         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1029         is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
1030
1031         $account->add_credit(
1032             {
1033                 amount      => $fines_amount,
1034                 interface   => 'test',
1035                 type        => 'PAYMENT',
1036                 description => "Some payment"
1037             }
1038         )->store;
1039         ( $renewokay, $error ) =
1040           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1041         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1042         is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit'  );
1043
1044         C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','0');
1045         ( $renewokay, $error ) =
1046           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1047         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1048         is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit'  );
1049
1050         $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
1051         C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
1052     };
1053
1054     subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
1055         plan tests => 6;
1056         my $item_to_auto_renew = $builder->build_sample_item(
1057             {
1058                 biblionumber => $biblio->biblionumber,
1059                 library      => $branch,
1060             }
1061         );
1062
1063         Koha::CirculationRules->set_rules(
1064             {
1065                 categorycode => undef,
1066                 branchcode   => undef,
1067                 itemtype     => undef,
1068                 rules        => {
1069                     norenewalbefore       => 10,
1070                     no_auto_renewal_after => 11,
1071                 }
1072             }
1073         );
1074
1075         my $ten_days_before = dt_from_string->add( days => -10 );
1076         my $ten_days_ahead = dt_from_string->add( days => 10 );
1077
1078         # Patron is expired and BlockExpiredPatronOpacActions=0
1079         # => auto renew is allowed
1080         t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
1081         my $patron = $expired_borrower;
1082         my $checkout = AddIssue( $patron, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1083         ( $renewokay, $error ) =
1084           CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->itemnumber );
1085         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1086         is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
1087         Koha::Checkouts->find( $checkout->issue_id )->delete;
1088
1089
1090         # Patron is expired and BlockExpiredPatronOpacActions=1
1091         # => auto renew is not allowed
1092         t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1093         $patron = $expired_borrower;
1094         $checkout = AddIssue( $patron, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1095         ( $renewokay, $error ) =
1096           CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->itemnumber );
1097         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1098         is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
1099         Koha::Checkouts->find( $checkout->issue_id )->delete;
1100
1101
1102         # Patron is not expired and BlockExpiredPatronOpacActions=1
1103         # => auto renew is allowed
1104         t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1105         $patron = $renewing_borrower;
1106         $checkout = AddIssue( $patron, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1107         ( $renewokay, $error ) =
1108           CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->itemnumber );
1109         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1110         is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
1111         Koha::Checkouts->find( $checkout->issue_id )->delete;
1112     };
1113
1114     subtest "GetLatestAutoRenewDate" => sub {
1115         plan tests => 5;
1116         my $item_to_auto_renew = $builder->build_sample_item(
1117             {
1118                 biblionumber => $biblio->biblionumber,
1119                 library      => $branch,
1120             }
1121         );
1122
1123         my $ten_days_before = dt_from_string->add( days => -10 );
1124         my $ten_days_ahead  = dt_from_string->add( days => 10 );
1125         AddIssue( $renewing_borrower, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1126         Koha::CirculationRules->set_rules(
1127             {
1128                 categorycode => undef,
1129                 branchcode   => undef,
1130                 itemtype     => undef,
1131                 rules        => {
1132                     norenewalbefore       => '7',
1133                     no_auto_renewal_after => '',
1134                     no_auto_renewal_after_hard_limit => undef,
1135                 }
1136             }
1137         );
1138         my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1139         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' );
1140         my $five_days_before = dt_from_string->add( days => -5 );
1141         Koha::CirculationRules->set_rules(
1142             {
1143                 categorycode => undef,
1144                 branchcode   => undef,
1145                 itemtype     => undef,
1146                 rules        => {
1147                     norenewalbefore       => '10',
1148                     no_auto_renewal_after => '5',
1149                     no_auto_renewal_after_hard_limit => undef,
1150                 }
1151             }
1152         );
1153         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1154         is( $latest_auto_renew_date->truncate( to => 'minute' ),
1155             $five_days_before->truncate( to => 'minute' ),
1156             'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
1157         );
1158         my $five_days_ahead = dt_from_string->add( days => 5 );
1159         $dbh->do(q{UPDATE circulation_rules SET rule_value = '10' WHERE rule_name = 'norenewalbefore'});
1160         $dbh->do(q{UPDATE circulation_rules SET rule_value = '15' WHERE rule_name = 'no_auto_renewal_after'});
1161         $dbh->do(q{UPDATE circulation_rules SET rule_value = NULL WHERE rule_name = 'no_auto_renewal_after_hard_limit'});
1162         Koha::CirculationRules->set_rules(
1163             {
1164                 categorycode => undef,
1165                 branchcode   => undef,
1166                 itemtype     => undef,
1167                 rules        => {
1168                     norenewalbefore       => '10',
1169                     no_auto_renewal_after => '15',
1170                     no_auto_renewal_after_hard_limit => undef,
1171                 }
1172             }
1173         );
1174         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1175         is( $latest_auto_renew_date->truncate( to => 'minute' ),
1176             $five_days_ahead->truncate( to => 'minute' ),
1177             'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
1178         );
1179         my $two_days_ahead = dt_from_string->add( days => 2 );
1180         Koha::CirculationRules->set_rules(
1181             {
1182                 categorycode => undef,
1183                 branchcode   => undef,
1184                 itemtype     => undef,
1185                 rules        => {
1186                     norenewalbefore       => '10',
1187                     no_auto_renewal_after => '',
1188                     no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1189                 }
1190             }
1191         );
1192         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1193         is( $latest_auto_renew_date->truncate( to => 'day' ),
1194             $two_days_ahead->truncate( to => 'day' ),
1195             'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
1196         );
1197         Koha::CirculationRules->set_rules(
1198             {
1199                 categorycode => undef,
1200                 branchcode   => undef,
1201                 itemtype     => undef,
1202                 rules        => {
1203                     norenewalbefore       => '10',
1204                     no_auto_renewal_after => '15',
1205                     no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1206                 }
1207             }
1208         );
1209         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1210         is( $latest_auto_renew_date->truncate( to => 'day' ),
1211             $two_days_ahead->truncate( to => 'day' ),
1212             'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
1213         );
1214
1215     };
1216     # Too many renewals
1217
1218     # set policy to forbid renewals
1219     Koha::CirculationRules->set_rules(
1220         {
1221             categorycode => undef,
1222             branchcode   => undef,
1223             itemtype     => undef,
1224             rules        => {
1225                 norenewalbefore => undef,
1226                 renewalsallowed => 0,
1227             }
1228         }
1229     );
1230
1231     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
1232     is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
1233     is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
1234
1235     # Too many unseen renewals
1236     Koha::CirculationRules->set_rules(
1237         {
1238             categorycode => undef,
1239             branchcode   => undef,
1240             itemtype     => undef,
1241             rules        => {
1242                 unseen_renewals_allowed => 2,
1243                 renewalsallowed => 10,
1244             }
1245         }
1246     );
1247     t::lib::Mocks::mock_preference('UnseenRenewals', 1);
1248     $dbh->do('UPDATE issues SET unseen_renewals = 2 where borrowernumber = ? AND itemnumber = ?', undef, ($renewing_borrowernumber, $item_1->itemnumber));
1249     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
1250     is( $renewokay, 0, 'Cannot renew, 0 unseen renewals allowed');
1251     is( $error, 'too_unseen', 'Cannot renew, returned code is too_unseen');
1252     Koha::CirculationRules->set_rules(
1253         {
1254             categorycode => undef,
1255             branchcode   => undef,
1256             itemtype     => undef,
1257             rules        => {
1258                 norenewalbefore => undef,
1259                 renewalsallowed => 0,
1260             }
1261         }
1262     );
1263     t::lib::Mocks::mock_preference('UnseenRenewals', 0);
1264
1265     # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
1266     t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
1267     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1268
1269     C4::Overdues::UpdateFine(
1270         {
1271             issue_id       => $issue->id(),
1272             itemnumber     => $item_1->itemnumber,
1273             borrowernumber => $renewing_borrower->{borrowernumber},
1274             amount         => 15.00,
1275             type           => q{},
1276             due            => Koha::DateUtils::output_pref($datedue)
1277         }
1278     );
1279
1280     my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower->{borrowernumber} })->next();
1281     is( $line->debit_type_code, 'OVERDUE', 'Account line type is OVERDUE' );
1282     is( $line->status, 'UNRETURNED', 'Account line status is UNRETURNED' );
1283     is( $line->amountoutstanding+0, 15, 'Account line amount outstanding is 15.00' );
1284     is( $line->amount+0, 15, 'Account line amount is 15.00' );
1285     is( $line->issue_id, $issue->id, 'Account line issue id matches' );
1286
1287     my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
1288     is( $offset->type, 'OVERDUE', 'Account offset type is Fine' );
1289     is( $offset->amount+0, 15, 'Account offset amount is 15.00' );
1290
1291     t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
1292     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
1293
1294     LostItem( $item_1->itemnumber, 'test', 1 );
1295
1296     $line = Koha::Account::Lines->find($line->id);
1297     is( $line->debit_type_code, 'OVERDUE', 'Account type remains as OVERDUE' );
1298     isnt( $line->status, 'UNRETURNED', 'Account status correctly changed from UNRETURNED to RETURNED' );
1299
1300     my $item = Koha::Items->find($item_1->itemnumber);
1301     ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
1302     my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
1303     is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
1304
1305     my $total_due = $dbh->selectrow_array(
1306         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1307         undef, $renewing_borrower->{borrowernumber}
1308     );
1309
1310     is( $total_due+0, 15, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
1311
1312     C4::Context->dbh->do("DELETE FROM accountlines");
1313
1314     C4::Overdues::UpdateFine(
1315         {
1316             issue_id       => $issue2->id(),
1317             itemnumber     => $item_2->itemnumber,
1318             borrowernumber => $renewing_borrower->{borrowernumber},
1319             amount         => 15.00,
1320             type           => q{},
1321             due            => Koha::DateUtils::output_pref($datedue)
1322         }
1323     );
1324
1325     LostItem( $item_2->itemnumber, 'test', 0 );
1326
1327     my $item2 = Koha::Items->find($item_2->itemnumber);
1328     ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
1329     ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
1330
1331     $total_due = $dbh->selectrow_array(
1332         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1333         undef, $renewing_borrower->{borrowernumber}
1334     );
1335
1336     ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
1337
1338     my $future = dt_from_string();
1339     $future->add( days => 7 );
1340     my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
1341     ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
1342
1343     my $manager = $builder->build_object({ class => "Koha::Patrons" });
1344     t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
1345     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1346     $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
1347     LostItem( $item_3->itemnumber, 'test', 0 );
1348     my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
1349     is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
1350     is(
1351         $accountline->description,
1352         sprintf( "%s %s %s",
1353             $item_3->biblio->title  || '',
1354             $item_3->barcode        || '',
1355             $item_3->itemcallnumber || '' ),
1356         "Account line description must not contain 'Lost Items ', but be title, barcode, itemcallnumber"
1357     );
1358 };
1359
1360 subtest "GetUpcomingDueIssues" => sub {
1361     plan tests => 12;
1362
1363     my $branch   = $library2->{branchcode};
1364
1365     #Create another record
1366     my $biblio2 = $builder->build_sample_biblio();
1367
1368     #Create third item
1369     my $item_1 = Koha::Items->find($reused_itemnumber_1);
1370     my $item_2 = Koha::Items->find($reused_itemnumber_2);
1371     my $item_3 = $builder->build_sample_item(
1372         {
1373             biblionumber     => $biblio2->biblionumber,
1374             library          => $branch,
1375             itype            => $itemtype,
1376         }
1377     );
1378
1379
1380     # Create a borrower
1381     my %a_borrower_data = (
1382         firstname =>  'Fridolyn',
1383         surname => 'SOMERS',
1384         categorycode => $patron_category->{categorycode},
1385         branchcode => $branch,
1386     );
1387
1388     my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1389     my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
1390
1391     my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
1392     my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
1393     my $today = DateTime->today(time_zone => C4::Context->tz());
1394
1395     my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
1396     my $datedue = dt_from_string( $issue->date_due() );
1397     my $issue2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
1398     my $datedue2 = dt_from_string( $issue->date_due() );
1399
1400     my $upcoming_dues;
1401
1402     # GetUpcomingDueIssues tests
1403     for my $i(0..1) {
1404         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1405         is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
1406     }
1407
1408     #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
1409     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1410     is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
1411
1412     for my $i(3..5) {
1413         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1414         is ( scalar( @$upcoming_dues ), 1,
1415             "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
1416     }
1417
1418     # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
1419
1420     my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
1421
1422     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
1423     is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
1424
1425     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
1426     is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
1427
1428     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
1429     is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
1430
1431     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 }  );
1432     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1433
1434     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1435     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1436
1437     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1438     is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1439
1440 };
1441
1442 subtest "Bug 13841 - Do not create new 0 amount fines" => sub {
1443     my $branch   = $library2->{branchcode};
1444
1445     my $biblio = $builder->build_sample_biblio();
1446
1447     #Create third item
1448     my $item = $builder->build_sample_item(
1449         {
1450             biblionumber     => $biblio->biblionumber,
1451             library          => $branch,
1452             itype            => $itemtype,
1453         }
1454     );
1455
1456     # Create a borrower
1457     my %a_borrower_data = (
1458         firstname =>  'Kyle',
1459         surname => 'Hall',
1460         categorycode => $patron_category->{categorycode},
1461         branchcode => $branch,
1462     );
1463
1464     my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1465
1466     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1467     my $issue = AddIssue( $borrower, $item->barcode );
1468     UpdateFine(
1469         {
1470             issue_id       => $issue->id(),
1471             itemnumber     => $item->itemnumber,
1472             borrowernumber => $borrowernumber,
1473             amount         => 0,
1474             type           => q{}
1475         }
1476     );
1477
1478     my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1479     my $count = $hr->{count};
1480
1481     is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1482 };
1483
1484 subtest "AllowRenewalIfOtherItemsAvailable tests" => sub {
1485     $dbh->do('DELETE FROM issues');
1486     $dbh->do('DELETE FROM items');
1487     $dbh->do('DELETE FROM circulation_rules');
1488     Koha::CirculationRules->set_rules(
1489         {
1490             categorycode => undef,
1491             itemtype     => undef,
1492             branchcode   => undef,
1493             rules        => {
1494                 reservesallowed => 25,
1495                 issuelength     => 14,
1496                 lengthunit      => 'days',
1497                 renewalsallowed => 1,
1498                 renewalperiod   => 7,
1499                 norenewalbefore => undef,
1500                 auto_renew      => 0,
1501                 fine            => .10,
1502                 chargeperiod    => 1,
1503                 maxissueqty     => 20
1504             }
1505         }
1506     );
1507     my $biblio = $builder->build_sample_biblio();
1508
1509     my $item_1 = $builder->build_sample_item(
1510         {
1511             biblionumber     => $biblio->biblionumber,
1512             library          => $library2->{branchcode},
1513             itype            => $itemtype,
1514         }
1515     );
1516
1517     my $item_2= $builder->build_sample_item(
1518         {
1519             biblionumber     => $biblio->biblionumber,
1520             library          => $library2->{branchcode},
1521             itype            => $itemtype,
1522         }
1523     );
1524
1525     my $borrowernumber1 = Koha::Patron->new({
1526         firstname    => 'Kyle',
1527         surname      => 'Hall',
1528         categorycode => $patron_category->{categorycode},
1529         branchcode   => $library2->{branchcode},
1530     })->store->borrowernumber;
1531     my $borrowernumber2 = Koha::Patron->new({
1532         firstname    => 'Chelsea',
1533         surname      => 'Hall',
1534         categorycode => $patron_category->{categorycode},
1535         branchcode   => $library2->{branchcode},
1536     })->store->borrowernumber;
1537
1538     my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1539     my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1540
1541     my $issue = AddIssue( $borrower1, $item_1->barcode );
1542
1543     my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1544     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1545
1546     AddReserve(
1547         {
1548             branchcode     => $library2->{branchcode},
1549             borrowernumber => $borrowernumber2,
1550             biblionumber   => $biblio->biblionumber,
1551             priority       => 1,
1552         }
1553     );
1554
1555     Koha::CirculationRules->set_rules(
1556         {
1557             categorycode => undef,
1558             itemtype     => undef,
1559             branchcode   => undef,
1560             rules        => {
1561                 onshelfholds => 0,
1562             }
1563         }
1564     );
1565     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1566     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1567     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1568
1569     Koha::CirculationRules->set_rules(
1570         {
1571             categorycode => undef,
1572             itemtype     => undef,
1573             branchcode   => undef,
1574             rules        => {
1575                 onshelfholds => 0,
1576             }
1577         }
1578     );
1579     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1580     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1581     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1582
1583     Koha::CirculationRules->set_rules(
1584         {
1585             categorycode => undef,
1586             itemtype     => undef,
1587             branchcode   => undef,
1588             rules        => {
1589                 onshelfholds => 1,
1590             }
1591         }
1592     );
1593     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1594     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1595     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1596
1597     Koha::CirculationRules->set_rules(
1598         {
1599             categorycode => undef,
1600             itemtype     => undef,
1601             branchcode   => undef,
1602             rules        => {
1603                 onshelfholds => 1,
1604             }
1605         }
1606     );
1607     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1608     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1609     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1610
1611     # Setting item not checked out to be not for loan but holdable
1612     $item_2->notforloan(-1)->store;
1613
1614     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1615     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' );
1616 };
1617
1618 {
1619     # Don't allow renewing onsite checkout
1620     my $branch   = $library->{branchcode};
1621
1622     #Create another record
1623     my $biblio = $builder->build_sample_biblio();
1624
1625     my $item = $builder->build_sample_item(
1626         {
1627             biblionumber     => $biblio->biblionumber,
1628             library          => $branch,
1629             itype            => $itemtype,
1630         }
1631     );
1632
1633     my $borrowernumber = Koha::Patron->new({
1634         firstname =>  'fn',
1635         surname => 'dn',
1636         categorycode => $patron_category->{categorycode},
1637         branchcode => $branch,
1638     })->store->borrowernumber;
1639
1640     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1641
1642     my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1643     my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $item->itemnumber );
1644     is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1645     is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1646 }
1647
1648 {
1649     my $library = $builder->build({ source => 'Branch' });
1650
1651     my $biblio = $builder->build_sample_biblio();
1652
1653     my $item = $builder->build_sample_item(
1654         {
1655             biblionumber     => $biblio->biblionumber,
1656             library          => $library->{branchcode},
1657             itype            => $itemtype,
1658         }
1659     );
1660
1661     my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1662
1663     my $issue = AddIssue( $patron, $item->barcode );
1664     UpdateFine(
1665         {
1666             issue_id       => $issue->id(),
1667             itemnumber     => $item->itemnumber,
1668             borrowernumber => $patron->{borrowernumber},
1669             amount         => 1,
1670             type           => q{}
1671         }
1672     );
1673     UpdateFine(
1674         {
1675             issue_id       => $issue->id(),
1676             itemnumber     => $item->itemnumber,
1677             borrowernumber => $patron->{borrowernumber},
1678             amount         => 2,
1679             type           => q{}
1680         }
1681     );
1682     is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1683 }
1684
1685 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1686     plan tests => 24;
1687
1688     my $homebranch    = $builder->build( { source => 'Branch' } );
1689     my $holdingbranch = $builder->build( { source => 'Branch' } );
1690     my $otherbranch   = $builder->build( { source => 'Branch' } );
1691     my $patron_1      = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1692     my $patron_2      = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1693
1694     my $item = $builder->build_sample_item(
1695         {
1696             homebranch    => $homebranch->{branchcode},
1697             holdingbranch => $holdingbranch->{branchcode},
1698         }
1699     );
1700
1701     set_userenv($holdingbranch);
1702
1703     my $issue = AddIssue( $patron_1->unblessed, $item->barcode );
1704     is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
1705
1706     my ( $error, $question, $alerts );
1707
1708     # AllowReturnToBranch == anywhere
1709     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1710     ## Test that unknown barcodes don't generate internal server errors
1711     set_userenv($homebranch);
1712     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1713     ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1714     ## Can be issued from homebranch
1715     set_userenv($homebranch);
1716     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1717     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1718     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1719     ## Can be issued from holdingbranch
1720     set_userenv($holdingbranch);
1721     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1722     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1723     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1724     ## Can be issued from another branch
1725     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1726     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1727     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1728
1729     # AllowReturnToBranch == holdingbranch
1730     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1731     ## Cannot be issued from homebranch
1732     set_userenv($homebranch);
1733     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1734     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1735     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1736     is( $error->{branch_to_return},         $holdingbranch->{branchcode}, 'branch_to_return matched holdingbranch' );
1737     ## Can be issued from holdinbranch
1738     set_userenv($holdingbranch);
1739     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1740     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1741     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1742     ## Cannot be issued from another branch
1743     set_userenv($otherbranch);
1744     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1745     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1746     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1747     is( $error->{branch_to_return},         $holdingbranch->{branchcode}, 'branch_to_return matches holdingbranch' );
1748
1749     # AllowReturnToBranch == homebranch
1750     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1751     ## Can be issued from holdinbranch
1752     set_userenv($homebranch);
1753     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1754     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1755     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1756     ## Cannot be issued from holdinbranch
1757     set_userenv($holdingbranch);
1758     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1759     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1760     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1761     is( $error->{branch_to_return},         $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1762     ## Cannot be issued from holdinbranch
1763     set_userenv($otherbranch);
1764     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1765     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1766     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1767     is( $error->{branch_to_return},         $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1768
1769     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1770 };
1771
1772 subtest 'AddIssue & AllowReturnToBranch' => sub {
1773     plan tests => 9;
1774
1775     my $homebranch    = $builder->build( { source => 'Branch' } );
1776     my $holdingbranch = $builder->build( { source => 'Branch' } );
1777     my $otherbranch   = $builder->build( { source => 'Branch' } );
1778     my $patron_1      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1779     my $patron_2      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1780
1781     my $item = $builder->build_sample_item(
1782         {
1783             homebranch    => $homebranch->{branchcode},
1784             holdingbranch => $holdingbranch->{branchcode},
1785         }
1786     );
1787
1788     set_userenv($holdingbranch);
1789
1790     my $ref_issue = 'Koha::Checkout';
1791     my $issue = AddIssue( $patron_1, $item->barcode );
1792
1793     my ( $error, $question, $alerts );
1794
1795     # AllowReturnToBranch == homebranch
1796     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1797     ## Can be issued from homebranch
1798     set_userenv($homebranch);
1799     is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from homebranch');
1800     set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
1801     ## Can be issued from holdinbranch
1802     set_userenv($holdingbranch);
1803     is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from holdingbranch');
1804     set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
1805     ## Can be issued from another branch
1806     set_userenv($otherbranch);
1807     is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from otherbranch');
1808     set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
1809
1810     # AllowReturnToBranch == holdinbranch
1811     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1812     ## Cannot be issued from homebranch
1813     set_userenv($homebranch);
1814     is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from homebranch');
1815     ## Can be issued from holdingbranch
1816     set_userenv($holdingbranch);
1817     is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - holdingbranch | Can be issued from holdingbranch');
1818     set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
1819     ## Cannot be issued from another branch
1820     set_userenv($otherbranch);
1821     is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from otherbranch');
1822
1823     # AllowReturnToBranch == homebranch
1824     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1825     ## Can be issued from homebranch
1826     set_userenv($homebranch);
1827     is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - homebranch | Can be issued from homebranch' );
1828     set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
1829     ## Cannot be issued from holdinbranch
1830     set_userenv($holdingbranch);
1831     is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from holdingbranch' );
1832     ## Cannot be issued from another branch
1833     set_userenv($otherbranch);
1834     is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from otherbranch' );
1835     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1836 };
1837
1838 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1839     plan tests => 8;
1840
1841     my $library = $builder->build( { source => 'Branch' } );
1842     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1843     my $item_1 = $builder->build_sample_item(
1844         {
1845             library => $library->{branchcode},
1846         }
1847     );
1848     my $item_2 = $builder->build_sample_item(
1849         {
1850             library => $library->{branchcode},
1851         }
1852     );
1853
1854     my ( $error, $question, $alerts );
1855
1856     # Patron cannot issue item_1, they have overdues
1857     my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1858     my $issue = AddIssue( $patron->unblessed, $item_1->barcode, $yesterday );    # Add an overdue
1859
1860     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1861     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
1862     is( keys(%$error) + keys(%$alerts),  0, 'No key for error and alert' . str($error, $question, $alerts) );
1863     is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
1864
1865     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1866     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
1867     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1868     is( $error->{USERBLOCKEDOVERDUE},      1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
1869
1870     # Patron cannot issue item_1, they are debarred
1871     my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1872     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
1873     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
1874     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1875     is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
1876
1877     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
1878     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
1879     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1880     is( $error->{USERBLOCKEDNOENDDATE},    '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
1881 };
1882
1883 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
1884     plan tests => 1;
1885
1886     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1887     my $patron_category_x = $builder->build_object(
1888         {
1889             class => 'Koha::Patron::Categories',
1890             value => { category_type => 'X' }
1891         }
1892     );
1893     my $patron = $builder->build_object(
1894         {
1895             class => 'Koha::Patrons',
1896             value => {
1897                 categorycode  => $patron_category_x->categorycode,
1898                 gonenoaddress => undef,
1899                 lost          => undef,
1900                 debarred      => undef,
1901                 borrowernotes => ""
1902             }
1903         }
1904     );
1905     my $item_1 = $builder->build_sample_item(
1906         {
1907             library => $library->{branchcode},
1908         }
1909     );
1910
1911     my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->barcode );
1912     is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
1913
1914     # TODO There are other tests to provide here
1915 };
1916
1917 subtest 'MultipleReserves' => sub {
1918     plan tests => 3;
1919
1920     my $biblio = $builder->build_sample_biblio();
1921
1922     my $branch = $library2->{branchcode};
1923
1924     my $item_1 = $builder->build_sample_item(
1925         {
1926             biblionumber     => $biblio->biblionumber,
1927             library          => $branch,
1928             replacementprice => 12.00,
1929             itype            => $itemtype,
1930         }
1931     );
1932
1933     my $item_2 = $builder->build_sample_item(
1934         {
1935             biblionumber     => $biblio->biblionumber,
1936             library          => $branch,
1937             replacementprice => 12.00,
1938             itype            => $itemtype,
1939         }
1940     );
1941
1942     my $bibitems       = '';
1943     my $priority       = '1';
1944     my $resdate        = undef;
1945     my $expdate        = undef;
1946     my $notes          = '';
1947     my $checkitem      = undef;
1948     my $found          = undef;
1949
1950     my %renewing_borrower_data = (
1951         firstname =>  'John',
1952         surname => 'Renewal',
1953         categorycode => $patron_category->{categorycode},
1954         branchcode => $branch,
1955     );
1956     my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
1957     my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
1958     my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
1959     my $datedue = dt_from_string( $issue->date_due() );
1960     is (defined $issue->date_due(), 1, "item 1 checked out");
1961     my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
1962
1963     my %reserving_borrower_data1 = (
1964         firstname =>  'Katrin',
1965         surname => 'Reservation',
1966         categorycode => $patron_category->{categorycode},
1967         branchcode => $branch,
1968     );
1969     my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
1970     AddReserve(
1971         {
1972             branchcode       => $branch,
1973             borrowernumber   => $reserving_borrowernumber1,
1974             biblionumber     => $biblio->biblionumber,
1975             priority         => $priority,
1976             reservation_date => $resdate,
1977             expiration_date  => $expdate,
1978             notes            => $notes,
1979             itemnumber       => $checkitem,
1980             found            => $found,
1981         }
1982     );
1983
1984     my %reserving_borrower_data2 = (
1985         firstname =>  'Kirk',
1986         surname => 'Reservation',
1987         categorycode => $patron_category->{categorycode},
1988         branchcode => $branch,
1989     );
1990     my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
1991     AddReserve(
1992         {
1993             branchcode       => $branch,
1994             borrowernumber   => $reserving_borrowernumber2,
1995             biblionumber     => $biblio->biblionumber,
1996             priority         => $priority,
1997             reservation_date => $resdate,
1998             expiration_date  => $expdate,
1999             notes            => $notes,
2000             itemnumber       => $checkitem,
2001             found            => $found,
2002         }
2003     );
2004
2005     {
2006         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
2007         is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
2008     }
2009
2010     my $item_3 = $builder->build_sample_item(
2011         {
2012             biblionumber     => $biblio->biblionumber,
2013             library          => $branch,
2014             replacementprice => 12.00,
2015             itype            => $itemtype,
2016         }
2017     );
2018
2019     {
2020         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
2021         is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
2022     }
2023 };
2024
2025 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
2026     plan tests => 5;
2027
2028     my $library = $builder->build( { source => 'Branch' } );
2029     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2030
2031     my $biblionumber = $builder->build_sample_biblio(
2032         {
2033             branchcode => $library->{branchcode},
2034         }
2035     )->biblionumber;
2036     my $item_1 = $builder->build_sample_item(
2037         {
2038             biblionumber => $biblionumber,
2039             library      => $library->{branchcode},
2040         }
2041     );
2042
2043     my $item_2 = $builder->build_sample_item(
2044         {
2045             biblionumber => $biblionumber,
2046             library      => $library->{branchcode},
2047         }
2048     );
2049
2050     my ( $error, $question, $alerts );
2051     my $issue = AddIssue( $patron->unblessed, $item_1->barcode, dt_from_string->add( days => 1 ) );
2052
2053     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2054     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2055     cmp_deeply(
2056         { error => $error, alerts => $alerts },
2057         { error => {}, alerts => {} },
2058         'No error or alert should be raised'
2059     );
2060     is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' );
2061
2062     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2063     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2064     cmp_deeply(
2065         { error => $error, question => $question, alerts => $alerts },
2066         { error => {}, question => {}, alerts => {} },
2067         'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1'
2068     );
2069
2070     # Add a subscription
2071     Koha::Subscription->new({ biblionumber => $biblionumber })->store;
2072
2073     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2074     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2075     cmp_deeply(
2076         { error => $error, question => $question, alerts => $alerts },
2077         { error => {}, question => {}, alerts => {} },
2078         'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2079     );
2080
2081     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2082     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2083     cmp_deeply(
2084         { error => $error, question => $question, alerts => $alerts },
2085         { error => {}, question => {}, alerts => {} },
2086         'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2087     );
2088 };
2089
2090 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
2091     plan tests => 8;
2092
2093     my $library = $builder->build( { source => 'Branch' } );
2094     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2095
2096     # Add 2 items
2097     my $biblionumber = $builder->build_sample_biblio(
2098         {
2099             branchcode => $library->{branchcode},
2100         }
2101     )->biblionumber;
2102     my $item_1 = $builder->build_sample_item(
2103         {
2104             biblionumber => $biblionumber,
2105             library      => $library->{branchcode},
2106         }
2107     );
2108     my $item_2 = $builder->build_sample_item(
2109         {
2110             biblionumber => $biblionumber,
2111             library      => $library->{branchcode},
2112         }
2113     );
2114
2115     # And the circulation rule
2116     Koha::CirculationRules->search->delete;
2117     Koha::CirculationRules->set_rules(
2118         {
2119             categorycode => undef,
2120             itemtype     => undef,
2121             branchcode   => undef,
2122             rules        => {
2123                 issuelength => 1,
2124                 firstremind => 1,        # 1 day of grace
2125                 finedays    => 2,        # 2 days of fine per day of overdue
2126                 lengthunit  => 'days',
2127             }
2128         }
2129     );
2130
2131     # Patron cannot issue item_1, they have overdues
2132     my $now = dt_from_string;
2133     my $five_days_ago = $now->clone->subtract( days => 5 );
2134     my $ten_days_ago  = $now->clone->subtract( days => 10 );
2135     AddIssue( $patron, $item_1->barcode, $five_days_ago );    # Add an overdue
2136     AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2137       ;    # Add another overdue
2138
2139     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
2140     AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2141     my $debarments = Koha::Patron::Debarments::GetDebarments(
2142         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2143     is( scalar(@$debarments), 1 );
2144
2145     # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
2146     # Same for the others
2147     my $expected_expiration = output_pref(
2148         {
2149             dt         => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2150             dateformat => 'sql',
2151             dateonly   => 1
2152         }
2153     );
2154     is( $debarments->[0]->{expiration}, $expected_expiration );
2155
2156     AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2157     $debarments = Koha::Patron::Debarments::GetDebarments(
2158         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2159     is( scalar(@$debarments), 1 );
2160     $expected_expiration = output_pref(
2161         {
2162             dt         => $now->clone->add( days => ( 10 - 1 ) * 2 ),
2163             dateformat => 'sql',
2164             dateonly   => 1
2165         }
2166     );
2167     is( $debarments->[0]->{expiration}, $expected_expiration );
2168
2169     Koha::Patron::Debarments::DelUniqueDebarment(
2170         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2171
2172     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
2173     AddIssue( $patron, $item_1->barcode, $five_days_ago );    # Add an overdue
2174     AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2175       ;    # Add another overdue
2176     AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2177     $debarments = Koha::Patron::Debarments::GetDebarments(
2178         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2179     is( scalar(@$debarments), 1 );
2180     $expected_expiration = output_pref(
2181         {
2182             dt         => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2183             dateformat => 'sql',
2184             dateonly   => 1
2185         }
2186     );
2187     is( $debarments->[0]->{expiration}, $expected_expiration );
2188
2189     AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2190     $debarments = Koha::Patron::Debarments::GetDebarments(
2191         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2192     is( scalar(@$debarments), 1 );
2193     $expected_expiration = output_pref(
2194         {
2195             dt => $now->clone->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
2196             dateformat => 'sql',
2197             dateonly   => 1
2198         }
2199     );
2200     is( $debarments->[0]->{expiration}, $expected_expiration );
2201 };
2202
2203 subtest 'AddReturn + suspension_chargeperiod' => sub {
2204     plan tests => 27;
2205
2206     my $library = $builder->build( { source => 'Branch' } );
2207     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2208
2209     my $biblionumber = $builder->build_sample_biblio(
2210         {
2211             branchcode => $library->{branchcode},
2212         }
2213     )->biblionumber;
2214     my $item_1 = $builder->build_sample_item(
2215         {
2216             biblionumber => $biblionumber,
2217             library      => $library->{branchcode},
2218         }
2219     );
2220
2221     # And the issuing rule
2222     Koha::CirculationRules->search->delete;
2223     Koha::CirculationRules->set_rules(
2224         {
2225             categorycode => '*',
2226             itemtype     => '*',
2227             branchcode   => '*',
2228             rules        => {
2229                 issuelength => 1,
2230                 firstremind => 0,    # 0 day of grace
2231                 finedays    => 2,    # 2 days of fine per day of overdue
2232                 suspension_chargeperiod => 1,
2233                 lengthunit              => 'days',
2234             }
2235         }
2236     );
2237
2238     my $now = dt_from_string;
2239     my $five_days_ago = $now->clone->subtract( days => 5 );
2240     # We want to charge 2 days every day, without grace
2241     # With 5 days of overdue: 5 * Z
2242     my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2243     test_debarment_on_checkout(
2244         {
2245             item            => $item_1,
2246             library         => $library,
2247             patron          => $patron,
2248             due_date        => $five_days_ago,
2249             expiration_date => $expected_expiration,
2250         }
2251     );
2252
2253     # Same with undef firstremind
2254     Koha::CirculationRules->search->delete;
2255     Koha::CirculationRules->set_rules(
2256         {
2257             categorycode => '*',
2258             itemtype     => '*',
2259             branchcode   => '*',
2260             rules        => {
2261                 issuelength => 1,
2262                 firstremind => undef,    # 0 day of grace
2263                 finedays    => 2,    # 2 days of fine per day of overdue
2264                 suspension_chargeperiod => 1,
2265                 lengthunit              => 'days',
2266             }
2267         }
2268     );
2269     {
2270     my $now = dt_from_string;
2271     my $five_days_ago = $now->clone->subtract( days => 5 );
2272     # We want to charge 2 days every day, without grace
2273     # With 5 days of overdue: 5 * Z
2274     my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2275     test_debarment_on_checkout(
2276         {
2277             item            => $item_1,
2278             library         => $library,
2279             patron          => $patron,
2280             due_date        => $five_days_ago,
2281             expiration_date => $expected_expiration,
2282         }
2283     );
2284     }
2285     # We want to charge 2 days every 2 days, without grace
2286     # With 5 days of overdue: (5 * 2) / 2
2287     Koha::CirculationRules->set_rule(
2288         {
2289             categorycode => undef,
2290             branchcode   => undef,
2291             itemtype     => undef,
2292             rule_name    => 'suspension_chargeperiod',
2293             rule_value   => '2',
2294         }
2295     );
2296
2297     $expected_expiration = $now->clone->add( days => floor( 5 * 2 ) / 2 );
2298     test_debarment_on_checkout(
2299         {
2300             item            => $item_1,
2301             library         => $library,
2302             patron          => $patron,
2303             due_date        => $five_days_ago,
2304             expiration_date => $expected_expiration,
2305         }
2306     );
2307
2308     # We want to charge 2 days every 3 days, with 1 day of grace
2309     # With 5 days of overdue: ((5-1) / 3 ) * 2
2310     Koha::CirculationRules->set_rules(
2311         {
2312             categorycode => undef,
2313             branchcode   => undef,
2314             itemtype     => undef,
2315             rules        => {
2316                 suspension_chargeperiod => 3,
2317                 firstremind             => 1,
2318             }
2319         }
2320     );
2321     $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
2322     test_debarment_on_checkout(
2323         {
2324             item            => $item_1,
2325             library         => $library,
2326             patron          => $patron,
2327             due_date        => $five_days_ago,
2328             expiration_date => $expected_expiration,
2329         }
2330     );
2331
2332     # Use finesCalendar to know if holiday must be skipped to calculate the due date
2333     # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
2334     Koha::CirculationRules->set_rules(
2335         {
2336             categorycode => undef,
2337             branchcode   => undef,
2338             itemtype     => undef,
2339             rules        => {
2340                 finedays                => 2,
2341                 suspension_chargeperiod => 1,
2342                 firstremind             => 0,
2343             }
2344         }
2345     );
2346     t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
2347     t::lib::Mocks::mock_preference('SuspensionsCalendar', 'noSuspensionsWhenClosed');
2348
2349     # Adding a holiday 2 days ago
2350     my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
2351     my $two_days_ago = $now->clone->subtract( days => 2 );
2352     $calendar->insert_single_holiday(
2353         day             => $two_days_ago->day,
2354         month           => $two_days_ago->month,
2355         year            => $two_days_ago->year,
2356         title           => 'holidayTest-2d',
2357         description     => 'holidayDesc 2 days ago'
2358     );
2359     # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
2360     $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
2361     test_debarment_on_checkout(
2362         {
2363             item            => $item_1,
2364             library         => $library,
2365             patron          => $patron,
2366             due_date        => $five_days_ago,
2367             expiration_date => $expected_expiration,
2368         }
2369     );
2370
2371     # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
2372     my $two_days_ahead = $now->clone->add( days => 2 );
2373     $calendar->insert_single_holiday(
2374         day             => $two_days_ahead->day,
2375         month           => $two_days_ahead->month,
2376         year            => $two_days_ahead->year,
2377         title           => 'holidayTest+2d',
2378         description     => 'holidayDesc 2 days ahead'
2379     );
2380
2381     # Same as above, but we should skip D+2
2382     $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
2383     test_debarment_on_checkout(
2384         {
2385             item            => $item_1,
2386             library         => $library,
2387             patron          => $patron,
2388             due_date        => $five_days_ago,
2389             expiration_date => $expected_expiration,
2390         }
2391     );
2392
2393     # Adding another holiday, day of expiration date
2394     my $expected_expiration_dt = dt_from_string($expected_expiration);
2395     $calendar->insert_single_holiday(
2396         day             => $expected_expiration_dt->day,
2397         month           => $expected_expiration_dt->month,
2398         year            => $expected_expiration_dt->year,
2399         title           => 'holidayTest_exp',
2400         description     => 'holidayDesc on expiration date'
2401     );
2402     # Expiration date will be the day after
2403     test_debarment_on_checkout(
2404         {
2405             item            => $item_1,
2406             library         => $library,
2407             patron          => $patron,
2408             due_date        => $five_days_ago,
2409             expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
2410         }
2411     );
2412
2413     test_debarment_on_checkout(
2414         {
2415             item            => $item_1,
2416             library         => $library,
2417             patron          => $patron,
2418             return_date     => $now->clone->add(days => 5),
2419             expiration_date => $now->clone->add(days => 5 + (5 * 2 - 1) ),
2420         }
2421     );
2422
2423     test_debarment_on_checkout(
2424         {
2425             item            => $item_1,
2426             library         => $library,
2427             patron          => $patron,
2428             due_date        => $now->clone->add(days => 1),
2429             return_date     => $now->clone->add(days => 5),
2430             expiration_date => $now->clone->add(days => 5 + (4 * 2 - 1) ),
2431         }
2432     );
2433
2434 };
2435
2436 subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
2437     plan tests => 2;
2438
2439     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2440     my $patron1 = $builder->build_object(
2441         {
2442             class => 'Koha::Patrons',
2443             value => {
2444                 library      => $library->branchcode,
2445                 categorycode => $patron_category->{categorycode}
2446             }
2447         }
2448     );
2449     my $patron2 = $builder->build_object(
2450         {
2451             class => 'Koha::Patrons',
2452             value => {
2453                 library      => $library->branchcode,
2454                 categorycode => $patron_category->{categorycode}
2455             }
2456         }
2457     );
2458
2459     t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
2460
2461     my $item = $builder->build_sample_item(
2462         {
2463             library      => $library->branchcode,
2464         }
2465     );
2466
2467     my ( $error, $question, $alerts );
2468     my $issue = AddIssue( $patron1->unblessed, $item->barcode );
2469
2470     t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2471     ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
2472     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' );
2473
2474     t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
2475     ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
2476     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' );
2477
2478     t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2479 };
2480
2481
2482 subtest 'AddReturn | is_overdue' => sub {
2483     plan tests => 9;
2484
2485     t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'batchmod|moredetail|cronjob|additem|pendingreserves|onpayment');
2486     t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
2487     t::lib::Mocks::mock_preference('finesMode', 'production');
2488     t::lib::Mocks::mock_preference('MaxFine', '100');
2489
2490     my $library = $builder->build( { source => 'Branch' } );
2491     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2492     my $manager = $builder->build_object({ class => "Koha::Patrons" });
2493     t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2494
2495     my $item = $builder->build_sample_item(
2496         {
2497             library      => $library->{branchcode},
2498             replacementprice => 7
2499         }
2500     );
2501
2502     Koha::CirculationRules->search->delete;
2503     Koha::CirculationRules->set_rules(
2504         {
2505             categorycode => undef,
2506             itemtype     => undef,
2507             branchcode   => undef,
2508             rules        => {
2509                 issuelength  => 6,
2510                 lengthunit   => 'days',
2511                 fine         => 1,        # Charge 1 every day of overdue
2512                 chargeperiod => 1,
2513             }
2514         }
2515     );
2516
2517     my $now   = dt_from_string;
2518     my $one_day_ago   = $now->clone->subtract( days => 1 );
2519     my $two_days_ago  = $now->clone->subtract( days => 2 );
2520     my $five_days_ago = $now->clone->subtract( days => 5 );
2521     my $ten_days_ago  = $now->clone->subtract( days => 10 );
2522     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
2523
2524     # No return date specified, today will be used => 10 days overdue charged
2525     AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2526     AddReturn( $item->barcode, $library->{branchcode} );
2527     is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
2528     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2529
2530     # specify return date 5 days before => no overdue charged
2531     AddIssue( $patron->unblessed, $item->barcode, $five_days_ago ); # date due was 5d ago
2532     AddReturn( $item->barcode, $library->{branchcode}, undef, $ten_days_ago );
2533     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2534     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2535
2536     # specify return date 5 days later => 5 days overdue charged
2537     AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2538     AddReturn( $item->barcode, $library->{branchcode}, undef, $five_days_ago );
2539     is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
2540     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2541
2542     # specify return date 5 days later, specify exemptfine => no overdue charge
2543     AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2544     AddReturn( $item->barcode, $library->{branchcode}, 1, $five_days_ago );
2545     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2546     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2547
2548     subtest 'bug 22877 | Lost item return' => sub {
2549
2550         plan tests => 3;
2551
2552         my $issue = AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );    # date due was 10d ago
2553
2554         # Fake fines cronjob on this checkout
2555         my ($fine) =
2556           CalcFine( $item, $patron->categorycode, $library->{branchcode},
2557             $ten_days_ago, $now );
2558         UpdateFine(
2559             {
2560                 issue_id       => $issue->issue_id,
2561                 itemnumber     => $item->itemnumber,
2562                 borrowernumber => $patron->borrowernumber,
2563                 amount         => $fine,
2564                 due            => output_pref($ten_days_ago)
2565             }
2566         );
2567         is( int( $patron->account->balance() ),
2568             10, "Overdue fine of 10 days overdue" );
2569
2570         # Fake longoverdue with charge and not marking returned
2571         LostItem( $item->itemnumber, 'cronjob', 0 );
2572         is( int( $patron->account->balance() ),
2573             17, "Lost fine of 7 plus 10 days overdue" );
2574
2575         # Now we return it today
2576         AddReturn( $item->barcode, $library->{branchcode} );
2577         is( int( $patron->account->balance() ),
2578             17, "Should have a single 10 days overdue fine and lost charge" );
2579
2580         # Cleanup
2581         Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2582     };
2583
2584     subtest 'bug 8338 | backdated return resulting in zero amount fine' => sub {
2585
2586         plan tests => 17;
2587
2588         t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
2589
2590         my $issue = AddIssue( $patron->unblessed, $item->barcode, $one_day_ago );    # date due was 1d ago
2591
2592         # Fake fines cronjob on this checkout
2593         my ($fine) =
2594           CalcFine( $item, $patron->categorycode, $library->{branchcode},
2595             $one_day_ago, $now );
2596         UpdateFine(
2597             {
2598                 issue_id       => $issue->issue_id,
2599                 itemnumber     => $item->itemnumber,
2600                 borrowernumber => $patron->borrowernumber,
2601                 amount         => $fine,
2602                 due            => output_pref($one_day_ago)
2603             }
2604         );
2605         is( int( $patron->account->balance() ),
2606             1, "Overdue fine of 1 day overdue" );
2607
2608         # Backdated return (dropbox mode example - charge should be removed)
2609         AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
2610         is( int( $patron->account->balance() ),
2611             0, "Overdue fine should be annulled" );
2612         my $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
2613         is( $lines->count, 0, "Overdue fine accountline has been removed");
2614
2615         $issue = AddIssue( $patron->unblessed, $item->barcode, $two_days_ago );    # date due was 2d ago
2616
2617         # Fake fines cronjob on this checkout
2618         ($fine) =
2619           CalcFine( $item, $patron->categorycode, $library->{branchcode},
2620             $two_days_ago, $now );
2621         UpdateFine(
2622             {
2623                 issue_id       => $issue->issue_id,
2624                 itemnumber     => $item->itemnumber,
2625                 borrowernumber => $patron->borrowernumber,
2626                 amount         => $fine,
2627                 due            => output_pref($one_day_ago)
2628             }
2629         );
2630         is( int( $patron->account->balance() ),
2631             2, "Overdue fine of 2 days overdue" );
2632
2633         # Payment made against fine
2634         $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
2635         my $debit = $lines->next;
2636         my $credit = $patron->account->add_credit(
2637             {
2638                 amount    => 2,
2639                 type      => 'PAYMENT',
2640                 interface => 'test',
2641             }
2642         );
2643         $credit->apply(
2644             { debits => [ $debit ], offset_type => 'Payment' } );
2645
2646         is( int( $patron->account->balance() ),
2647             0, "Overdue fine should be paid off" );
2648         $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
2649         is ( $lines->count, 2, "Overdue (debit) and Payment (credit) present");
2650         my $line = $lines->next;
2651         is( $line->amount+0, 2, "Overdue fine amount remains as 2 days");
2652         is( $line->amountoutstanding+0, 0, "Overdue fine amountoutstanding reduced to 0");
2653
2654         # Backdated return (dropbox mode example - charge should be removed)
2655         AddReturn( $item->barcode, $library->{branchcode}, undef, $one_day_ago );
2656         is( int( $patron->account->balance() ),
2657             -1, "Refund credit has been applied" );
2658         $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber }, { order_by => { '-asc' => 'accountlines_id' }});
2659         is( $lines->count, 3, "Overdue (debit), Payment (credit) and Refund (credit) are all present");
2660
2661         $line = $lines->next;
2662         is($line->amount+0,1, "Overdue fine amount has been reduced to 1");
2663         is($line->amountoutstanding+0,0, "Overdue fine amount outstanding remains at 0");
2664         is($line->status,'RETURNED', "Overdue fine is fixed");
2665         $line = $lines->next;
2666         is($line->amount+0,-2, "Original payment amount remains as 2");
2667         is($line->amountoutstanding+0,0, "Original payment remains applied");
2668         $line = $lines->next;
2669         is($line->amount+0,-1, "Refund amount correctly set to 1");
2670         is($line->amountoutstanding+0,-1, "Refund amount outstanding unspent");
2671
2672         # Cleanup
2673         Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2674     };
2675
2676     subtest 'bug 25417 | backdated return + exemptfine' => sub {
2677
2678         plan tests => 2;
2679
2680         t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
2681
2682         my $issue = AddIssue( $patron->unblessed, $item->barcode, $one_day_ago );    # date due was 1d ago
2683
2684         # Fake fines cronjob on this checkout
2685         my ($fine) =
2686           CalcFine( $item, $patron->categorycode, $library->{branchcode},
2687             $one_day_ago, $now );
2688         UpdateFine(
2689             {
2690                 issue_id       => $issue->issue_id,
2691                 itemnumber     => $item->itemnumber,
2692                 borrowernumber => $patron->borrowernumber,
2693                 amount         => $fine,
2694                 due            => output_pref($one_day_ago)
2695             }
2696         );
2697         is( int( $patron->account->balance() ),
2698             1, "Overdue fine of 1 day overdue" );
2699
2700         # Backdated return (dropbox mode example - charge should no longer exist)
2701         AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
2702         is( int( $patron->account->balance() ),
2703             0, "Overdue fine should be annulled" );
2704
2705         # Cleanup
2706         Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2707     };
2708
2709     subtest 'bug 24075 | backdated return with return datetime matching due datetime' => sub {
2710         plan tests => 7;
2711
2712         t::lib::Mocks::mock_preference( 'CalculateFinesOnBackdate', 1 );
2713
2714         my $due_date = dt_from_string;
2715         my $issue = AddIssue( $patron->unblessed, $item->barcode, $due_date );
2716
2717         # Add fine
2718         UpdateFine(
2719             {
2720                 issue_id       => $issue->issue_id,
2721                 itemnumber     => $item->itemnumber,
2722                 borrowernumber => $patron->borrowernumber,
2723                 amount         => 0.25,
2724                 due            => output_pref($due_date)
2725             }
2726         );
2727         is( $patron->account->balance(),
2728             0.25, 'Overdue fine of $0.25 recorded' );
2729
2730         # Backdate return to exact due date and time
2731         my ( undef, $message ) =
2732           AddReturn( $item->barcode, $library->{branchcode},
2733             undef, $due_date );
2734
2735         my $accountline =
2736           Koha::Account::Lines->find( { issue_id => $issue->id } );
2737         ok( !$accountline, 'accountline removed as expected' );
2738
2739         # Re-issue
2740         $issue = AddIssue( $patron->unblessed, $item->barcode, $due_date );
2741
2742         # Add fine
2743         UpdateFine(
2744             {
2745                 issue_id       => $issue->issue_id,
2746                 itemnumber     => $item->itemnumber,
2747                 borrowernumber => $patron->borrowernumber,
2748                 amount         => .25,
2749                 due            => output_pref($due_date)
2750             }
2751         );
2752         is( $patron->account->balance(),
2753             0.25, 'Overdue fine of $0.25 recorded' );
2754
2755         # Partial pay accruing fine
2756         my $lines = Koha::Account::Lines->search(
2757             {
2758                 borrowernumber => $patron->borrowernumber,
2759                 issue_id       => $issue->id
2760             }
2761         );
2762         my $debit  = $lines->next;
2763         my $credit = $patron->account->add_credit(
2764             {
2765                 amount    => .20,
2766                 type      => 'PAYMENT',
2767                 interface => 'test',
2768             }
2769         );
2770         $credit->apply( { debits => [$debit], offset_type => 'Payment' } );
2771
2772         is( $patron->account->balance(), .05, 'Overdue fine reduced to $0.05' );
2773
2774         # Backdate return to exact due date and time
2775         ( undef, $message ) =
2776           AddReturn( $item->barcode, $library->{branchcode},
2777             undef, $due_date );
2778
2779         $lines = Koha::Account::Lines->search(
2780             {
2781                 borrowernumber => $patron->borrowernumber,
2782                 issue_id       => $issue->id
2783             }
2784         );
2785         $accountline = $lines->next;
2786         is( $accountline->amountoutstanding + 0,
2787             0, 'Partially paid fee amount outstanding was reduced to 0' );
2788         is( $accountline->amount + 0,
2789             0, 'Partially paid fee amount was reduced to 0' );
2790         is( $patron->account->balance(), -0.20, 'Patron refund recorded' );
2791
2792         # Cleanup
2793         Koha::Account::Lines->search(
2794             { borrowernumber => $patron->borrowernumber } )->delete;
2795     };
2796
2797     subtest 'enh 23091 | Lost item return policies' => sub {
2798         plan tests => 4;
2799
2800         my $manager = $builder->build_object({ class => "Koha::Patrons" });
2801
2802         my $branchcode_false =
2803           $builder->build( { source => 'Branch' } )->{branchcode};
2804         my $specific_rule_false = $builder->build(
2805             {
2806                 source => 'CirculationRule',
2807                 value  => {
2808                     branchcode   => $branchcode_false,
2809                     categorycode => undef,
2810                     itemtype     => undef,
2811                     rule_name    => 'lostreturn',
2812                     rule_value   => 0
2813                 }
2814             }
2815         );
2816         my $branchcode_refund =
2817           $builder->build( { source => 'Branch' } )->{branchcode};
2818         my $specific_rule_refund = $builder->build(
2819             {
2820                 source => 'CirculationRule',
2821                 value  => {
2822                     branchcode   => $branchcode_refund,
2823                     categorycode => undef,
2824                     itemtype     => undef,
2825                     rule_name    => 'lostreturn',
2826                     rule_value   => 'refund'
2827                 }
2828             }
2829         );
2830         my $branchcode_restore =
2831           $builder->build( { source => 'Branch' } )->{branchcode};
2832         my $specific_rule_restore = $builder->build(
2833             {
2834                 source => 'CirculationRule',
2835                 value  => {
2836                     branchcode   => $branchcode_restore,
2837                     categorycode => undef,
2838                     itemtype     => undef,
2839                     rule_name    => 'lostreturn',
2840                     rule_value   => 'restore'
2841                 }
2842             }
2843         );
2844         my $branchcode_charge =
2845           $builder->build( { source => 'Branch' } )->{branchcode};
2846         my $specific_rule_charge = $builder->build(
2847             {
2848                 source => 'CirculationRule',
2849                 value  => {
2850                     branchcode   => $branchcode_charge,
2851                     categorycode => undef,
2852                     itemtype     => undef,
2853                     rule_name    => 'lostreturn',
2854                     rule_value   => 'charge'
2855                 }
2856             }
2857         );
2858
2859         my $replacement_amount = 99.00;
2860         t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
2861         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
2862         t::lib::Mocks::mock_preference( 'WhenLostForgiveFine',          0 );
2863         t::lib::Mocks::mock_preference( 'BlockReturnOfLostItems',       0 );
2864         t::lib::Mocks::mock_preference( 'RefundLostOnReturnControl',
2865             'CheckinLibrary' );
2866         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge',
2867             undef );
2868
2869         subtest 'lostreturn | false' => sub {
2870             plan tests => 12;
2871
2872             t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_false });
2873
2874             my $item = $builder->build_sample_item(
2875                 {
2876                     replacementprice => $replacement_amount
2877                 }
2878             );
2879
2880             # Issue the item
2881             my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
2882
2883             # Fake fines cronjob on this checkout
2884             my ($fine) =
2885               CalcFine( $item, $patron->categorycode, $library->{branchcode},
2886                 $ten_days_ago, $now );
2887             UpdateFine(
2888                 {
2889                     issue_id       => $issue->issue_id,
2890                     itemnumber     => $item->itemnumber,
2891                     borrowernumber => $patron->borrowernumber,
2892                     amount         => $fine,
2893                     due            => output_pref($ten_days_ago)
2894                 }
2895             );
2896             my $overdue_fees = Koha::Account::Lines->search(
2897                 {
2898                     borrowernumber  => $patron->id,
2899                     itemnumber      => $item->itemnumber,
2900                     debit_type_code => 'OVERDUE'
2901                 }
2902             );
2903             is( $overdue_fees->count, 1, 'Overdue item fee produced' );
2904             my $overdue_fee = $overdue_fees->next;
2905             is( $overdue_fee->amount + 0,
2906                 10, 'The right OVERDUE amount is generated' );
2907             is( $overdue_fee->amountoutstanding + 0,
2908                 10,
2909                 'The right OVERDUE amountoutstanding is generated' );
2910
2911             # Simulate item marked as lost
2912             $item->itemlost(3)->store;
2913             C4::Circulation::LostItem( $item->itemnumber, 1 );
2914
2915             my $lost_fee_lines = Koha::Account::Lines->search(
2916                 {
2917                     borrowernumber  => $patron->id,
2918                     itemnumber      => $item->itemnumber,
2919                     debit_type_code => 'LOST'
2920                 }
2921             );
2922             is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
2923             my $lost_fee_line = $lost_fee_lines->next;
2924             is( $lost_fee_line->amount + 0,
2925                 $replacement_amount, 'The right LOST amount is generated' );
2926             is( $lost_fee_line->amountoutstanding + 0,
2927                 $replacement_amount,
2928                 'The right LOST amountoutstanding is generated' );
2929             is( $lost_fee_line->status, undef, 'The LOST status was not set' );
2930
2931             # Return lost item
2932             my ( $returned, $message ) =
2933               AddReturn( $item->barcode, $branchcode_false, undef, $five_days_ago );
2934
2935             $overdue_fee->discard_changes;
2936             is( $overdue_fee->amount + 0,
2937                 10, 'The OVERDUE amount is left intact' );
2938             is( $overdue_fee->amountoutstanding + 0,
2939                 10,
2940                 'The OVERDUE amountoutstanding is left intact' );
2941
2942             $lost_fee_line->discard_changes;
2943             is( $lost_fee_line->amount + 0,
2944                 $replacement_amount, 'The LOST amount is left intact' );
2945             is( $lost_fee_line->amountoutstanding + 0,
2946                 $replacement_amount,
2947                 'The LOST amountoutstanding is left intact' );
2948             # FIXME: Should we set the LOST fee status to 'FOUND' regardless of whether we're refunding or not?
2949             is( $lost_fee_line->status, undef, 'The LOST status was not set' );
2950         };
2951
2952         subtest 'lostreturn | refund' => sub {
2953             plan tests => 12;
2954
2955             t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_refund });
2956
2957             my $item = $builder->build_sample_item(
2958                 {
2959                     replacementprice => $replacement_amount
2960                 }
2961             );
2962
2963             # Issue the item
2964             my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
2965
2966             # Fake fines cronjob on this checkout
2967             my ($fine) =
2968               CalcFine( $item, $patron->categorycode, $library->{branchcode},
2969                 $ten_days_ago, $now );
2970             UpdateFine(
2971                 {
2972                     issue_id       => $issue->issue_id,
2973                     itemnumber     => $item->itemnumber,
2974                     borrowernumber => $patron->borrowernumber,
2975                     amount         => $fine,
2976                     due            => output_pref($ten_days_ago)
2977                 }
2978             );
2979             my $overdue_fees = Koha::Account::Lines->search(
2980                 {
2981                     borrowernumber  => $patron->id,
2982                     itemnumber      => $item->itemnumber,
2983                     debit_type_code => 'OVERDUE'
2984                 }
2985             );
2986             is( $overdue_fees->count, 1, 'Overdue item fee produced' );
2987             my $overdue_fee = $overdue_fees->next;
2988             is( $overdue_fee->amount + 0,
2989                 10, 'The right OVERDUE amount is generated' );
2990             is( $overdue_fee->amountoutstanding + 0,
2991                 10,
2992                 'The right OVERDUE amountoutstanding is generated' );
2993
2994             # Simulate item marked as lost
2995             $item->itemlost(3)->store;
2996             C4::Circulation::LostItem( $item->itemnumber, 1 );
2997
2998             my $lost_fee_lines = Koha::Account::Lines->search(
2999                 {
3000                     borrowernumber  => $patron->id,
3001                     itemnumber      => $item->itemnumber,
3002                     debit_type_code => 'LOST'
3003                 }
3004             );
3005             is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3006             my $lost_fee_line = $lost_fee_lines->next;
3007             is( $lost_fee_line->amount + 0,
3008                 $replacement_amount, 'The right LOST amount is generated' );
3009             is( $lost_fee_line->amountoutstanding + 0,
3010                 $replacement_amount,
3011                 'The right LOST amountoutstanding is generated' );
3012             is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3013
3014             # Return the lost item
3015             my ( undef, $message ) =
3016               AddReturn( $item->barcode, $branchcode_refund, undef, $five_days_ago );
3017
3018             $overdue_fee->discard_changes;
3019             is( $overdue_fee->amount + 0,
3020                 10, 'The OVERDUE amount is left intact' );
3021             is( $overdue_fee->amountoutstanding + 0,
3022                 10,
3023                 'The OVERDUE amountoutstanding is left intact' );
3024
3025             $lost_fee_line->discard_changes;
3026             is( $lost_fee_line->amount + 0,
3027                 $replacement_amount, 'The LOST amount is left intact' );
3028             is( $lost_fee_line->amountoutstanding + 0,
3029                 0,
3030                 'The LOST amountoutstanding is refunded' );
3031             is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3032         };
3033
3034         subtest 'lostreturn | restore' => sub {
3035             plan tests => 13;
3036
3037             t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_restore });
3038
3039             my $item = $builder->build_sample_item(
3040                 {
3041                     replacementprice => $replacement_amount
3042                 }
3043             );
3044
3045             # Issue the item
3046             my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode , $ten_days_ago);
3047
3048             # Fake fines cronjob on this checkout
3049             my ($fine) =
3050               CalcFine( $item, $patron->categorycode, $library->{branchcode},
3051                 $ten_days_ago, $now );
3052             UpdateFine(
3053                 {
3054                     issue_id       => $issue->issue_id,
3055                     itemnumber     => $item->itemnumber,
3056                     borrowernumber => $patron->borrowernumber,
3057                     amount         => $fine,
3058                     due            => output_pref($ten_days_ago)
3059                 }
3060             );
3061             my $overdue_fees = Koha::Account::Lines->search(
3062                 {
3063                     borrowernumber  => $patron->id,
3064                     itemnumber      => $item->itemnumber,
3065                     debit_type_code => 'OVERDUE'
3066                 }
3067             );
3068             is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3069             my $overdue_fee = $overdue_fees->next;
3070             is( $overdue_fee->amount + 0,
3071                 10, 'The right OVERDUE amount is generated' );
3072             is( $overdue_fee->amountoutstanding + 0,
3073                 10,
3074                 'The right OVERDUE amountoutstanding is generated' );
3075
3076             # Simulate item marked as lost
3077             $item->itemlost(3)->store;
3078             C4::Circulation::LostItem( $item->itemnumber, 1 );
3079
3080             my $lost_fee_lines = Koha::Account::Lines->search(
3081                 {
3082                     borrowernumber  => $patron->id,
3083                     itemnumber      => $item->itemnumber,
3084                     debit_type_code => 'LOST'
3085                 }
3086             );
3087             is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3088             my $lost_fee_line = $lost_fee_lines->next;
3089             is( $lost_fee_line->amount + 0,
3090                 $replacement_amount, 'The right LOST amount is generated' );
3091             is( $lost_fee_line->amountoutstanding + 0,
3092                 $replacement_amount,
3093                 'The right LOST amountoutstanding is generated' );
3094             is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3095
3096             # Simulate refunding overdue fees upon marking item as lost
3097             my $overdue_forgive = $patron->account->add_credit(
3098                 {
3099                     amount     => 10.00,
3100                     user_id    => $manager->borrowernumber,
3101                     library_id => $branchcode_restore,
3102                     interface  => 'test',
3103                     type       => 'FORGIVEN',
3104                     item_id    => $item->itemnumber
3105                 }
3106             );
3107             $overdue_forgive->apply(
3108                 { debits => [$overdue_fee], offset_type => 'Forgiven' } );
3109             $overdue_fee->discard_changes;
3110             is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3111
3112             # Do nothing
3113             my ( undef, $message ) =
3114               AddReturn( $item->barcode, $branchcode_restore, undef, $five_days_ago );
3115
3116             $overdue_fee->discard_changes;
3117             is( $overdue_fee->amount + 0,
3118                 10, 'The OVERDUE amount is left intact' );
3119             is( $overdue_fee->amountoutstanding + 0,
3120                 10,
3121                 'The OVERDUE amountoutstanding is restored' );
3122
3123             $lost_fee_line->discard_changes;
3124             is( $lost_fee_line->amount + 0,
3125                 $replacement_amount, 'The LOST amount is left intact' );
3126             is( $lost_fee_line->amountoutstanding + 0,
3127                 0,
3128                 'The LOST amountoutstanding is refunded' );
3129             is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3130         };
3131
3132         subtest 'lostreturn | charge' => sub {
3133             plan tests => 16;
3134
3135             t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_charge });
3136
3137             my $item = $builder->build_sample_item(
3138                 {
3139                     replacementprice => $replacement_amount
3140                 }
3141             );
3142
3143             # Issue the item
3144             my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3145
3146             # Fake fines cronjob on this checkout
3147             my ($fine) =
3148               CalcFine( $item, $patron->categorycode, $library->{branchcode},
3149                 $ten_days_ago, $now );
3150             UpdateFine(
3151                 {
3152                     issue_id       => $issue->issue_id,
3153                     itemnumber     => $item->itemnumber,
3154                     borrowernumber => $patron->borrowernumber,
3155                     amount         => $fine,
3156                     due            => output_pref($ten_days_ago)
3157                 }
3158             );
3159             my $overdue_fees = Koha::Account::Lines->search(
3160                 {
3161                     borrowernumber  => $patron->id,
3162                     itemnumber      => $item->itemnumber,
3163                     debit_type_code => 'OVERDUE'
3164                 }
3165             );
3166             is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3167             my $overdue_fee = $overdue_fees->next;
3168             is( $overdue_fee->amount + 0,
3169                 10, 'The right OVERDUE amount is generated' );
3170             is( $overdue_fee->amountoutstanding + 0,
3171                 10,
3172                 'The right OVERDUE amountoutstanding is generated' );
3173
3174             # Simulate item marked as lost
3175             $item->itemlost(3)->store;
3176             C4::Circulation::LostItem( $item->itemnumber, 1 );
3177
3178             my $lost_fee_lines = Koha::Account::Lines->search(
3179                 {
3180                     borrowernumber  => $patron->id,
3181                     itemnumber      => $item->itemnumber,
3182                     debit_type_code => 'LOST'
3183                 }
3184             );
3185             is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3186             my $lost_fee_line = $lost_fee_lines->next;
3187             is( $lost_fee_line->amount + 0,
3188                 $replacement_amount, 'The right LOST amount is generated' );
3189             is( $lost_fee_line->amountoutstanding + 0,
3190                 $replacement_amount,
3191                 'The right LOST amountoutstanding is generated' );
3192             is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3193
3194             # Simulate refunding overdue fees upon marking item as lost
3195             my $overdue_forgive = $patron->account->add_credit(
3196                 {
3197                     amount     => 10.00,
3198                     user_id    => $manager->borrowernumber,
3199                     library_id => $branchcode_charge,
3200                     interface  => 'test',
3201                     type       => 'FORGIVEN',
3202                     item_id    => $item->itemnumber
3203                 }
3204             );
3205             $overdue_forgive->apply(
3206                 { debits => [$overdue_fee], offset_type => 'Forgiven' } );
3207             $overdue_fee->discard_changes;
3208             is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3209
3210             # Do nothing
3211             my ( undef, $message ) =
3212               AddReturn( $item->barcode, $branchcode_charge, undef, $five_days_ago );
3213
3214             $lost_fee_line->discard_changes;
3215             is( $lost_fee_line->amount + 0,
3216                 $replacement_amount, 'The LOST amount is left intact' );
3217             is( $lost_fee_line->amountoutstanding + 0,
3218                 0,
3219                 'The LOST amountoutstanding is refunded' );
3220             is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3221
3222             $overdue_fees = Koha::Account::Lines->search(
3223                 {
3224                     borrowernumber  => $patron->id,
3225                     itemnumber      => $item->itemnumber,
3226                     debit_type_code => 'OVERDUE'
3227                 },
3228                 {
3229                     order_by => { '-asc' => 'accountlines_id'}
3230                 }
3231             );
3232             is( $overdue_fees->count, 2, 'A second OVERDUE fee has been added' );
3233             $overdue_fee = $overdue_fees->next;
3234             is( $overdue_fee->amount + 0,
3235                 10, 'The original OVERDUE amount is left intact' );
3236             is( $overdue_fee->amountoutstanding + 0,
3237                 0,
3238                 'The original OVERDUE amountoutstanding is left as forgiven' );
3239             $overdue_fee = $overdue_fees->next;
3240             is( $overdue_fee->amount + 0,
3241                 5, 'The new OVERDUE amount is correct for the backdated return' );
3242             is( $overdue_fee->amountoutstanding + 0,
3243                 5,
3244                 'The new OVERDUE amountoutstanding is correct for the backdated return' );
3245         };
3246     };
3247 };
3248
3249 subtest '_FixOverduesOnReturn' => sub {
3250     plan tests => 14;
3251
3252     my $manager = $builder->build_object({ class => "Koha::Patrons" });
3253     t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
3254
3255     my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
3256
3257     my $branchcode  = $library2->{branchcode};
3258
3259     my $item = $builder->build_sample_item(
3260         {
3261             biblionumber     => $biblio->biblionumber,
3262             library          => $branchcode,
3263             replacementprice => 99.00,
3264             itype            => $itemtype,
3265         }
3266     );
3267
3268     my $patron = $builder->build( { source => 'Borrower' } );
3269
3270     ## Start with basic call, should just close out the open fine
3271     my $accountline = Koha::Account::Line->new(
3272         {
3273             borrowernumber => $patron->{borrowernumber},
3274             debit_type_code    => 'OVERDUE',
3275             status         => 'UNRETURNED',
3276             itemnumber     => $item->itemnumber,
3277             amount => 99.00,
3278             amountoutstanding => 99.00,
3279             interface => 'test',
3280         }
3281     )->store();
3282
3283     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, undef, 'RETURNED' );
3284
3285     $accountline->_result()->discard_changes();
3286
3287     is( $accountline->amountoutstanding+0, 99, 'Fine has the same amount outstanding as previously' );
3288     isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3289     is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3290
3291     ## Run again, with exemptfine enabled
3292     $accountline->set(
3293         {
3294             debit_type_code    => 'OVERDUE',
3295             status         => 'UNRETURNED',
3296             amountoutstanding => 99.00,
3297         }
3298     )->store();
3299
3300     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3301
3302     $accountline->_result()->discard_changes();
3303     my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
3304
3305     is( $accountline->amountoutstanding + 0, 0, 'Fine amountoutstanding has been reduced to 0' );
3306     isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3307     is( $accountline->status, 'RETURNED', 'Open fine ( account type OVERDUE ) has been set to returned ( status RETURNED )');
3308     is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
3309     is( $offset->amount + 0, -99, "Amount of offset is correct" );
3310     my $credit = $offset->credit;
3311     is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
3312     is( $credit->amount + 0, -99, "Credit amount is set correctly" );
3313     is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
3314
3315     # Bug 25417 - Only forgive fines where there is an amount outstanding to forgive
3316     $accountline->set(
3317         {
3318             debit_type_code    => 'OVERDUE',
3319             status         => 'UNRETURNED',
3320             amountoutstanding => 0.00,
3321         }
3322     )->store();
3323     $offset->delete;
3324
3325     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3326
3327     $accountline->_result()->discard_changes();
3328     $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
3329     is( $offset, undef, "No offset created when trying to forgive fine with no outstanding balance" );
3330     isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3331     is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3332 };
3333
3334 subtest 'Set waiting flag' => sub {
3335     plan tests => 11;
3336
3337     my $library_1 = $builder->build( { source => 'Branch' } );
3338     my $patron_1  = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3339     my $library_2 = $builder->build( { source => 'Branch' } );
3340     my $patron_2  = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3341
3342     my $item = $builder->build_sample_item(
3343         {
3344             library      => $library_1->{branchcode},
3345         }
3346     );
3347
3348     set_userenv( $library_2 );
3349     my $reserve_id = AddReserve(
3350         {
3351             branchcode     => $library_2->{branchcode},
3352             borrowernumber => $patron_2->{borrowernumber},
3353             biblionumber   => $item->biblionumber,
3354             priority       => 1,
3355             itemnumber     => $item->itemnumber,
3356         }
3357     );
3358
3359     set_userenv( $library_1 );
3360     my $do_transfer = 1;
3361     my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
3362     ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
3363     my $hold = Koha::Holds->find( $reserve_id );
3364     is( $hold->found, 'T', 'Hold is in transit' );
3365
3366     my ( $status ) = CheckReserves($item->itemnumber);
3367     is( $status, 'Transferred', 'Hold is not waiting yet');
3368
3369     set_userenv( $library_2 );
3370     $do_transfer = 0;
3371     AddReturn( $item->barcode, $library_2->{branchcode} );
3372     ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
3373     $hold = Koha::Holds->find( $reserve_id );
3374     is( $hold->found, 'W', 'Hold is waiting' );
3375     ( $status ) = CheckReserves($item->itemnumber);
3376     is( $status, 'Waiting', 'Now the hold is waiting');
3377
3378     #Bug 21944 - Waiting transfer checked in at branch other than pickup location
3379     set_userenv( $library_1 );
3380     (undef, my $messages, undef, undef ) = AddReturn ( $item->barcode, $library_1->{branchcode} );
3381     $hold = Koha::Holds->find( $reserve_id );
3382     is( $hold->found, undef, 'Hold is no longer marked waiting' );
3383     is( $hold->priority, 1,  "Hold is now priority one again");
3384     is( $hold->waitingdate, undef, "Hold no longer has a waiting date");
3385     is( $hold->itemnumber, $item->itemnumber, "Hold has retained its' itemnumber");
3386     is( $messages->{ResFound}->{ResFound}, "Reserved", "Hold is still returned");
3387     is( $messages->{ResFound}->{found}, undef, "Hold is no longer marked found in return message");
3388     is( $messages->{ResFound}->{priority}, 1, "Hold is priority 1 in return message");
3389 };
3390
3391 subtest 'Cancel transfers on lost items' => sub {
3392     plan tests => 6;
3393     my $library_1 = $builder->build( { source => 'Branch' } );
3394     my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3395     my $library_2 = $builder->build( { source => 'Branch' } );
3396     my $patron_2  = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3397     my $biblio = $builder->build_sample_biblio({branchcode => $library->{branchcode}});
3398     my $item   = $builder->build_sample_item({
3399         biblionumber  => $biblio->biblionumber,
3400         library    => $library_1->{branchcode},
3401     });
3402
3403     set_userenv( $library_2 );
3404     my $reserve_id = AddReserve(
3405         {
3406             branchcode     => $library_2->{branchcode},
3407             borrowernumber => $patron_2->{borrowernumber},
3408             biblionumber   => $item->biblionumber,
3409             priority       => 1,
3410             itemnumber     => $item->itemnumber,
3411         }
3412     );
3413
3414     #Return book and add transfer
3415     set_userenv( $library_1 );
3416     my $do_transfer = 1;
3417     my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
3418     ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
3419     C4::Circulation::transferbook({
3420         from_branch => $library_1->{branchcode},
3421         to_branch => $library_2->{branchcode},
3422         barcode   => $item->barcode,
3423         trigger   => 'Reserve',
3424     });
3425     my $hold = Koha::Holds->find( $reserve_id );
3426     is( $hold->found, 'T', 'Hold is in transit' );
3427
3428     #Check transfer exists and the items holding branch is the transfer destination branch before marking it as lost
3429     my ($datesent,$frombranch,$tobranch) = GetTransfers($item->itemnumber);
3430     is( $frombranch, $library_1->{branchcode}, 'The transfer is generated from the correct library');
3431     is( $tobranch, $library_2->{branchcode}, 'The transfer is generated to the correct library');
3432     my $itemcheck = Koha::Items->find($item->itemnumber);
3433     is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Items holding branch is the transfers origination branch before it is marked as lost' );
3434
3435     #Simulate item being marked as lost and confirm the transfer is deleted and the items holding branch is the transfers source branch
3436     $item->itemlost(1)->store;
3437     LostItem( $item->itemnumber, 'test', 1 );
3438     ($datesent,$frombranch,$tobranch) = GetTransfers($item->itemnumber);
3439     is( $tobranch, undef, 'The transfer on the lost item has been deleted as the LostItemCancelOutstandingTransfer is enabled');
3440     $itemcheck = Koha::Items->find($item->itemnumber);
3441     is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Lost item with cancelled hold has holding branch equallying the transfers source branch' );
3442
3443 };
3444
3445 subtest 'CanBookBeIssued | is_overdue' => sub {
3446     plan tests => 3;
3447
3448     # Set a simple circ policy
3449     Koha::CirculationRules->set_rules(
3450         {
3451             categorycode => undef,
3452             branchcode   => undef,
3453             itemtype     => undef,
3454             rules        => {
3455                 maxissueqty     => 1,
3456                 reservesallowed => 25,
3457                 issuelength     => 14,
3458                 lengthunit      => 'days',
3459                 renewalsallowed => 1,
3460                 renewalperiod   => 7,
3461                 norenewalbefore => undef,
3462                 auto_renew      => 0,
3463                 fine            => .10,
3464                 chargeperiod    => 1,
3465             }
3466         }
3467     );
3468
3469     my $now   = dt_from_string;
3470     my $five_days_go = output_pref({ dt => $now->clone->add( days => 5 ), dateonly => 1});
3471     my $ten_days_go  = output_pref({ dt => $now->clone->add( days => 10), dateonly => 1 });
3472     my $library = $builder->build( { source => 'Branch' } );
3473     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
3474
3475     my $item = $builder->build_sample_item(
3476         {
3477             library      => $library->{branchcode},
3478         }
3479     );
3480
3481     my $issue = AddIssue( $patron->unblessed, $item->barcode, $five_days_go ); # date due was 10d ago
3482     my $actualissue = Koha::Checkouts->find( { itemnumber => $item->itemnumber } );
3483     is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
3484     my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->barcode,$ten_days_go, undef, undef, undef);
3485     is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
3486     is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
3487 };
3488
3489 subtest 'ItemsDeniedRenewal preference' => sub {
3490     plan tests => 18;
3491
3492     C4::Context->set_preference('ItemsDeniedRenewal','');
3493
3494     my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
3495     Koha::CirculationRules->set_rules(
3496         {
3497             categorycode => '*',
3498             itemtype     => '*',
3499             branchcode   => $idr_lib->branchcode,
3500             rules        => {
3501                 reservesallowed => 25,
3502                 issuelength     => 14,
3503                 lengthunit      => 'days',
3504                 renewalsallowed => 10,
3505                 renewalperiod   => 7,
3506                 norenewalbefore => undef,
3507                 auto_renew      => 0,
3508                 fine            => .10,
3509                 chargeperiod    => 1,
3510             }
3511         }
3512     );
3513
3514     my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
3515         homebranch => $idr_lib->branchcode,
3516         withdrawn => 1,
3517         itype => 'HIDE',
3518         location => 'PROC',
3519         itemcallnumber => undef,
3520         itemnotes => "",
3521         }
3522     });
3523     my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
3524         homebranch => $idr_lib->branchcode,
3525         withdrawn => 0,
3526         itype => 'NOHIDE',
3527         location => 'NOPROC'
3528         }
3529     });
3530
3531     my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
3532         branchcode => $idr_lib->branchcode,
3533         }
3534     });
3535     my $future = dt_from_string->add( days => 1 );
3536     my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3537         returndate => undef,
3538         renewals => 0,
3539         auto_renew => 0,
3540         borrowernumber => $idr_borrower->borrowernumber,
3541         itemnumber => $deny_book->itemnumber,
3542         onsite_checkout => 0,
3543         date_due => $future,
3544         }
3545     });
3546     my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3547         returndate => undef,
3548         renewals => 0,
3549         auto_renew => 0,
3550         borrowernumber => $idr_borrower->borrowernumber,
3551         itemnumber => $allow_book->itemnumber,
3552         onsite_checkout => 0,
3553         date_due => $future,
3554         }
3555     });
3556
3557     my $idr_rules;
3558
3559     my ( $idr_mayrenew, $idr_error ) =
3560     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3561     is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
3562     is( $idr_error, undef, 'Renewal allowed when no rules' );
3563
3564     $idr_rules="withdrawn: [1]";
3565
3566     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3567     ( $idr_mayrenew, $idr_error ) =
3568     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3569     is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
3570     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
3571     ( $idr_mayrenew, $idr_error ) =
3572     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3573     is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3574     is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3575
3576     $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
3577
3578     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3579     ( $idr_mayrenew, $idr_error ) =
3580     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3581     is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
3582     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
3583     ( $idr_mayrenew, $idr_error ) =
3584     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3585     is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3586     is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3587
3588     $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
3589
3590     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3591     ( $idr_mayrenew, $idr_error ) =
3592     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3593     is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
3594     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
3595     ( $idr_mayrenew, $idr_error ) =
3596     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3597     is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
3598     is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
3599
3600     $idr_rules="itemcallnumber: [NULL]";
3601     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3602     ( $idr_mayrenew, $idr_error ) =
3603     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3604     is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
3605     $idr_rules="itemcallnumber: ['']";
3606     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3607     ( $idr_mayrenew, $idr_error ) =
3608     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3609     is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
3610
3611     $idr_rules="itemnotes: [NULL]";
3612     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3613     ( $idr_mayrenew, $idr_error ) =
3614     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3615     is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
3616     $idr_rules="itemnotes: ['']";
3617     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3618     ( $idr_mayrenew, $idr_error ) =
3619     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3620     is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
3621 };
3622
3623 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
3624     plan tests => 2;
3625
3626     t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
3627     my $library = $builder->build( { source => 'Branch' } );
3628     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
3629
3630     my $item = $builder->build_sample_item(
3631         {
3632             library      => $library->{branchcode},
3633         }
3634     );
3635
3636     my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3637     is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3638     is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3639 };
3640
3641 subtest 'CanBookBeIssued | notforloan' => sub {
3642     plan tests => 2;
3643
3644     t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
3645
3646     my $library = $builder->build( { source => 'Branch' } );
3647     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
3648
3649     my $itemtype = $builder->build(
3650         {
3651             source => 'Itemtype',
3652             value  => { notforloan => undef, }
3653         }
3654     );
3655     my $item = $builder->build_sample_item(
3656         {
3657             library  => $library->{branchcode},
3658             itype    => $itemtype->{itemtype},
3659         }
3660     );
3661     $item->biblioitem->itemtype($itemtype->{itemtype})->store;
3662
3663     my ( $issuingimpossible, $needsconfirmation );
3664
3665
3666     subtest 'item-level_itypes = 1' => sub {
3667         plan tests => 6;
3668
3669         t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
3670         # Is for loan at item type and item level
3671         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3672         is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3673         is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3674
3675         # not for loan at item type level
3676         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
3677         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3678         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3679         is_deeply(
3680             $issuingimpossible,
3681             { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
3682             'Item can not be issued, not for loan at item type level'
3683         );
3684
3685         # not for loan at item level
3686         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
3687         $item->notforloan( 1 )->store;
3688         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3689         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3690         is_deeply(
3691             $issuingimpossible,
3692             { NOT_FOR_LOAN => 1, item_notforloan => 1 },
3693             'Item can not be issued, not for loan at item type level'
3694         );
3695     };
3696
3697     subtest 'item-level_itypes = 0' => sub {
3698         plan tests => 6;
3699
3700         t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
3701
3702         # We set another itemtype for biblioitem
3703         my $itemtype = $builder->build(
3704             {
3705                 source => 'Itemtype',
3706                 value  => { notforloan => undef, }
3707             }
3708         );
3709
3710         # for loan at item type and item level
3711         $item->notforloan(0)->store;
3712         $item->biblioitem->itemtype($itemtype->{itemtype})->store;
3713         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3714         is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3715         is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3716
3717         # not for loan at item type level
3718         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
3719         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3720         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3721         is_deeply(
3722             $issuingimpossible,
3723             { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
3724             'Item can not be issued, not for loan at item type level'
3725         );
3726
3727         # not for loan at item level
3728         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
3729         $item->notforloan( 1 )->store;
3730         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3731         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3732         is_deeply(
3733             $issuingimpossible,
3734             { NOT_FOR_LOAN => 1, item_notforloan => 1 },
3735             'Item can not be issued, not for loan at item type level'
3736         );
3737     };
3738
3739     # TODO test with AllowNotForLoanOverride = 1
3740 };
3741
3742 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
3743     plan tests => 1;
3744
3745     t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
3746     my $item = $builder->build_sample_item(
3747         {
3748             onloan => '2018-01-01',
3749         }
3750     );
3751
3752     AddReturn( $item->barcode, $item->homebranch );
3753     $item->discard_changes; # refresh
3754     is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
3755 };
3756
3757
3758 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
3759
3760     plan tests => 13;
3761
3762
3763     t::lib::Mocks::mock_preference('item-level_itypes', 1);
3764
3765     my $issuing_charges = 15;
3766     my $title   = 'A title';
3767     my $author  = 'Author, An';
3768     my $barcode = 'WHATARETHEODDS';
3769
3770     my $circ = Test::MockModule->new('C4::Circulation');
3771     $circ->mock(
3772         'GetIssuingCharges',
3773         sub {
3774             return $issuing_charges;
3775         }
3776     );
3777
3778     my $library  = $builder->build_object({ class => 'Koha::Libraries' });
3779     my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
3780     my $patron   = $builder->build_object({
3781         class => 'Koha::Patrons',
3782         value => { branchcode => $library->id }
3783     });
3784
3785     my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
3786     my $item_id = Koha::Item->new(
3787         {
3788             biblionumber     => $biblio->biblionumber,
3789             homebranch       => $library->id,
3790             holdingbranch    => $library->id,
3791             barcode          => $barcode,
3792             replacementprice => 23.00,
3793             itype            => $itemtype->id
3794         },
3795     )->store->itemnumber;
3796     my $item = Koha::Items->find( $item_id );
3797
3798     my $context = Test::MockModule->new('C4::Context');
3799     $context->mock( userenv => { branch => $library->id } );
3800
3801     # Check the item out
3802     AddIssue( $patron->unblessed, $item->barcode );
3803
3804     throws_ok {
3805         AddRenewal( $patron->borrowernumber, $item->itemnumber, $library->id, undef, {break=>"the_renewal"} );
3806     } 'Koha::Exceptions::Checkout::FailedRenewal', 'Exception is thrown when renewal update to issues fails';
3807
3808     t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
3809     my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
3810     my %params_renewal = (
3811         timestamp => { -like => $date . "%" },
3812         module => "CIRCULATION",
3813         action => "RENEWAL",
3814     );
3815     my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
3816     AddRenewal( $patron->id, $item->id, $library->id );
3817     my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3818     is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
3819
3820     my $checkouts = $patron->checkouts;
3821     # The following will fail if run on 00:00:00
3822     unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
3823
3824     my $lines = Koha::Account::Lines->search({
3825         borrowernumber => $patron->id,
3826         itemnumber     => $item->id
3827     });
3828
3829     is( $lines->count, 2 );
3830
3831     my $line = $lines->next;
3832     is( $line->debit_type_code, 'RENT',       'The issue of item with issuing charge generates an accountline of the correct type' );
3833     is( $line->branchcode,  $library->id, 'AddIssuingCharge correctly sets branchcode' );
3834     is( $line->description, '',     'AddIssue does not set a hardcoded description for the accountline' );
3835
3836     $line = $lines->next;
3837     is( $line->debit_type_code, 'RENT_RENEW', 'The renewal of item with issuing charge generates an accountline of the correct type' );
3838     is( $line->branchcode,  $library->id, 'AddRenewal correctly sets branchcode' );
3839     is( $line->description, '', 'AddRenewal does not set a hardcoded description for the accountline' );
3840
3841     t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
3842
3843     $context = Test::MockModule->new('C4::Context');
3844     $context->mock( userenv => { branch => undef, interface => 'CRON'} ); #Test statistical logging of renewal via cron (atuo_renew)
3845
3846     my $now = dt_from_string;
3847     $date = output_pref( { dt => $now, dateonly => 1, dateformat => 'iso' } );
3848     $old_log_size = Koha::ActionLogs->count( \%params_renewal );
3849     my $sth = $dbh->prepare("SELECT COUNT(*) FROM statistics WHERE itemnumber = ? AND branch = ?");
3850     $sth->execute($item->id, $library->id);
3851     my ($old_stats_size) = $sth->fetchrow_array;
3852     AddRenewal( $patron->id, $item->id, $library->id );
3853     $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3854     $sth->execute($item->id, $library->id);
3855     my ($new_stats_size) = $sth->fetchrow_array;
3856     is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
3857     is( $new_stats_size, $old_stats_size + 1, 'renew statistic successfully added with passed branch' );
3858
3859     AddReturn( $item->id, $library->id, undef, $date );
3860     AddIssue( $patron->unblessed, $item->barcode, $now );
3861     AddRenewal( $patron->id, $item->id, $library->id, undef, undef, 1 );
3862     my $lines_skipped = Koha::Account::Lines->search({
3863         borrowernumber => $patron->id,
3864         itemnumber     => $item->id
3865     });
3866     is( $lines_skipped->count, 5, 'Passing skipfinecalc causes fine calculation on renewal to be skipped' );
3867
3868 };
3869
3870 subtest 'ProcessOfflinePayment() tests' => sub {
3871
3872     plan tests => 4;
3873
3874
3875     my $amount = 123;
3876
3877     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
3878     my $library = $builder->build_object({ class => 'Koha::Libraries' });
3879     my $result  = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
3880
3881     is( $result, 'Success.', 'The right string is returned' );
3882
3883     my $lines = $patron->account->lines;
3884     is( $lines->count, 1, 'line created correctly');
3885
3886     my $line = $lines->next;
3887     is( $line->amount+0, $amount * -1, 'amount picked from params' );
3888     is( $line->branchcode, $library->id, 'branchcode set correctly' );
3889
3890 };
3891
3892 subtest 'Incremented fee tests' => sub {
3893     plan tests => 19;
3894
3895     my $dt = dt_from_string();
3896     Time::Fake->offset( $dt->epoch );
3897
3898     t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
3899
3900     my $library =
3901       $builder->build_object( { class => 'Koha::Libraries' } )->store;
3902
3903     $module->mock( 'userenv', sub { { branch => $library->id } } );
3904
3905     my $patron = $builder->build_object(
3906         {
3907             class => 'Koha::Patrons',
3908             value => { categorycode => $patron_category->{categorycode} }
3909         }
3910     )->store;
3911
3912     my $itemtype = $builder->build_object(
3913         {
3914             class => 'Koha::ItemTypes',
3915             value => {
3916                 notforloan                   => undef,
3917                 rentalcharge                 => 0,
3918                 rentalcharge_daily           => 1,
3919                 rentalcharge_daily_calendar  => 0
3920             }
3921         }
3922     )->store;
3923
3924     my $item = $builder->build_sample_item(
3925         {
3926             library  => $library->{branchcode},
3927             itype    => $itemtype->id,
3928         }
3929     );
3930
3931     is( $itemtype->rentalcharge_daily+0,
3932         1, 'Daily rental charge stored and retreived correctly' );
3933     is( $item->effective_itemtype, $itemtype->id,
3934         "Itemtype set correctly for item" );
3935
3936     my $now         = dt_from_string;
3937     my $dt_from     = $now->clone;
3938     my $dt_to       = $now->clone->add( days => 7 );
3939     my $dt_to_renew = $now->clone->add( days => 13 );
3940
3941     # Daily Tests
3942     my $issue =
3943       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3944     my $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3945     is( $accountline->amount+0, 7,
3946 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0"
3947     );
3948     $accountline->delete();
3949     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3950     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3951     is( $accountline->amount+0, 6,
3952 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0, for renewal"
3953     );
3954     $accountline->delete();
3955     $issue->delete();
3956
3957     t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
3958     $itemtype->rentalcharge_daily_calendar(1)->store();
3959     $issue =
3960       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3961     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3962     is( $accountline->amount+0, 7,
3963 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1"
3964     );
3965     $accountline->delete();
3966     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3967     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3968     is( $accountline->amount+0, 6,
3969 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1, for renewal"
3970     );
3971     $accountline->delete();
3972     $issue->delete();
3973
3974     my $calendar = C4::Calendar->new( branchcode => $library->id );
3975     # DateTime 1..7 (Mon..Sun), C4::Calender 0..6 (Sun..Sat)
3976     my $closed_day =
3977         ( $dt_from->day_of_week == 6 ) ? 0
3978       : ( $dt_from->day_of_week == 7 ) ? 1
3979       :                                  $dt_from->day_of_week + 1;
3980     my $closed_day_name = $dt_from->clone->add(days => 1)->day_name;
3981     $calendar->insert_week_day_holiday(
3982         weekday     => $closed_day,
3983         title       => 'Test holiday',
3984         description => 'Test holiday'
3985     );
3986     $issue =
3987       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3988     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3989     is( $accountline->amount+0, 6,
3990 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name"
3991     );
3992     $accountline->delete();
3993     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3994     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3995     is( $accountline->amount+0, 5,
3996 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name, for renewal"
3997     );
3998     $accountline->delete();
3999     $issue->delete();
4000
4001     $itemtype->rentalcharge(2)->store;
4002     is( $itemtype->rentalcharge+0, 2,
4003         'Rental charge updated and retreived correctly' );
4004     $issue =
4005       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4006     my $accountlines =
4007       Koha::Account::Lines->search( { itemnumber => $item->id } );
4008     is( $accountlines->count, '2',
4009         "Fixed charge and accrued charge recorded distinctly" );
4010     $accountlines->delete();
4011     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4012     $accountlines = Koha::Account::Lines->search( { itemnumber => $item->id } );
4013     is( $accountlines->count, '2',
4014         "Fixed charge and accrued charge recorded distinctly, for renewal" );
4015     $accountlines->delete();
4016     $issue->delete();
4017     $itemtype->rentalcharge(0)->store;
4018     is( $itemtype->rentalcharge+0, 0,
4019         'Rental charge reset and retreived correctly' );
4020
4021     # Hourly
4022     Koha::CirculationRules->set_rule(
4023         {
4024             categorycode => $patron->categorycode,
4025             itemtype     => $itemtype->id,
4026             branchcode   => $library->id,
4027             rule_name    => 'lengthunit',
4028             rule_value   => 'hours',
4029         }
4030     );
4031
4032     $itemtype->rentalcharge_hourly('0.25')->store();
4033     is( $itemtype->rentalcharge_hourly,
4034         '0.25', 'Hourly rental charge stored and retreived correctly' );
4035
4036     $dt_to       = $now->clone->add( hours => 168 );
4037     $dt_to_renew = $now->clone->add( hours => 312 );
4038
4039     $itemtype->rentalcharge_hourly_calendar(0)->store();
4040     $issue =
4041       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4042     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4043     is( $accountline->amount + 0, 42,
4044         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0 (168h * 0.25u)" );
4045     $accountline->delete();
4046     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4047     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4048     is( $accountline->amount + 0, 36,
4049         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0, for renewal (312h - 168h * 0.25u)" );
4050     $accountline->delete();
4051     $issue->delete();
4052
4053     $itemtype->rentalcharge_hourly_calendar(1)->store();
4054     $issue =
4055       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4056     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4057     is( $accountline->amount + 0, 36,
4058         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name (168h - 24h * 0.25u)" );
4059     $accountline->delete();
4060     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4061     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4062     is( $accountline->amount + 0, 30,
4063         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name, for renewal (312h - 168h - 24h * 0.25u" );
4064     $accountline->delete();
4065     $issue->delete();
4066
4067     $calendar->delete_holiday( weekday => $closed_day );
4068     $issue =
4069       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4070     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4071     is( $accountline->amount + 0, 42,
4072         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 (168h - 0h * 0.25u" );
4073     $accountline->delete();
4074     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4075     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4076     is( $accountline->amount + 0, 36,
4077         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1, for renewal (312h - 168h - 0h * 0.25u)" );
4078     $accountline->delete();
4079     $issue->delete();
4080     Time::Fake->reset;
4081 };
4082
4083 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
4084     plan tests => 2;
4085
4086     t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
4087     t::lib::Mocks::mock_preference('item-level_itypes', 1);
4088
4089     my $library =
4090       $builder->build_object( { class => 'Koha::Libraries' } )->store;
4091     my $patron = $builder->build_object(
4092         {
4093             class => 'Koha::Patrons',
4094             value => { categorycode => $patron_category->{categorycode} }
4095         }
4096     )->store;
4097
4098     my $itemtype = $builder->build_object(
4099         {
4100             class => 'Koha::ItemTypes',
4101             value => {
4102                 notforloan             => 0,
4103                 rentalcharge           => 0,
4104                 rentalcharge_daily => 0
4105             }
4106         }
4107     );
4108
4109     my $item = $builder->build_sample_item(
4110         {
4111             library    => $library->id,
4112             notforloan => 0,
4113             itemlost   => 0,
4114             withdrawn  => 0,
4115             itype      => $itemtype->id,
4116         }
4117     )->store;
4118
4119     my ( $issuingimpossible, $needsconfirmation );
4120     my $dt_from = dt_from_string();
4121     my $dt_due = $dt_from->clone->add( days => 3 );
4122
4123     $itemtype->rentalcharge(1)->store;
4124     ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4125     is_deeply( $needsconfirmation, { RENTALCHARGE => '1.00' }, 'Item needs rentalcharge confirmation to be issued' );
4126     $itemtype->rentalcharge('0')->store;
4127     $itemtype->rentalcharge_daily(1)->store;
4128     ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4129     is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
4130     $itemtype->rentalcharge_daily('0')->store;
4131 };
4132
4133 subtest 'CanBookBeIssued & CircConfirmItemParts' => sub {
4134     plan tests => 1;
4135
4136     t::lib::Mocks::mock_preference('CircConfirmItemParts', 1);
4137
4138     my $patron = $builder->build_object(
4139         {
4140             class => 'Koha::Patrons',
4141             value => { categorycode => $patron_category->{categorycode} }
4142         }
4143     )->store;
4144
4145     my $item = $builder->build_sample_item(
4146         {
4147             materials => 'includes DVD',
4148         }
4149     )->store;
4150
4151     my $dt_due = dt_from_string->add( days => 3 );
4152
4153     my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4154     is_deeply( $needsconfirmation, { ADDITIONAL_MATERIALS => 'includes DVD' }, 'Item needs confirmation of additional parts' );
4155 };
4156
4157 subtest 'Do not return on renewal (LOST charge)' => sub {
4158     plan tests => 1;
4159
4160     t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'onpayment');
4161     my $library = $builder->build_object( { class => "Koha::Libraries" } );
4162     my $manager = $builder->build_object( { class => "Koha::Patrons" } );
4163     t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
4164
4165     my $biblio = $builder->build_sample_biblio;
4166
4167     my $item = $builder->build_sample_item(
4168         {
4169             biblionumber     => $biblio->biblionumber,
4170             library          => $library->branchcode,
4171             replacementprice => 99.00,
4172             itype            => $itemtype,
4173         }
4174     );
4175
4176     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
4177     AddIssue( $patron->unblessed, $item->barcode );
4178
4179     my $accountline = Koha::Account::Line->new(
4180         {
4181             borrowernumber    => $patron->borrowernumber,
4182             debit_type_code   => 'LOST',
4183             status            => undef,
4184             itemnumber        => $item->itemnumber,
4185             amount            => 12,
4186             amountoutstanding => 12,
4187             interface         => 'something',
4188         }
4189     )->store();
4190
4191     # AddRenewal doesn't call _FixAccountForLostAndFound
4192     AddIssue( $patron->unblessed, $item->barcode );
4193
4194     is( $patron->checkouts->count, 1,
4195         'Renewal should not return the item even if a LOST payment has been made earlier'
4196     );
4197 };
4198
4199 subtest 'Filling a hold should cancel existing transfer' => sub {
4200     plan tests => 4;
4201
4202     t::lib::Mocks::mock_preference('AutomaticItemReturn', 1);
4203
4204     my $libraryA = $builder->build_object( { class => 'Koha::Libraries' } );
4205     my $libraryB = $builder->build_object( { class => 'Koha::Libraries' } );
4206     my $patron = $builder->build_object(
4207         {
4208             class => 'Koha::Patrons',
4209             value => {
4210                 categorycode => $patron_category->{categorycode},
4211                 branchcode => $libraryA->branchcode,
4212             }
4213         }
4214     )->store;
4215
4216     my $item = $builder->build_sample_item({
4217         homebranch => $libraryB->branchcode,
4218     });
4219
4220     my ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
4221     is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 1, "We generate a transfer on checkin");
4222     AddReserve({
4223         branchcode     => $libraryA->branchcode,
4224         borrowernumber => $patron->borrowernumber,
4225         biblionumber   => $item->biblionumber,
4226         itemnumber     => $item->itemnumber
4227     });
4228     my $reserves = Koha::Holds->search({ itemnumber => $item->itemnumber });
4229     is( $reserves->count, 1, "Reserve is placed");
4230     ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
4231     my $reserve = $reserves->next;
4232     ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 0, $reserve->reserve_id );
4233     $reserve->discard_changes;
4234     ok( $reserve->found eq 'W', "Reserve is marked waiting" );
4235     is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 0, "No outstanding transfers when hold is waiting");
4236 };
4237
4238 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddReturn' => sub {
4239
4240     plan tests => 4;
4241
4242     t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
4243     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
4244     my $patron  = $builder->build_object(
4245         {
4246             class => 'Koha::Patrons',
4247             value => { categorycode => $patron_category->{categorycode} }
4248         }
4249     );
4250
4251     my $biblionumber = $builder->build_sample_biblio(
4252         {
4253             branchcode => $library->branchcode,
4254         }
4255     )->biblionumber;
4256
4257     # And the circulation rule
4258     Koha::CirculationRules->search->delete;
4259     Koha::CirculationRules->set_rules(
4260         {
4261             categorycode => undef,
4262             itemtype     => undef,
4263             branchcode   => undef,
4264             rules        => {
4265                 issuelength => 14,
4266                 lengthunit  => 'days',
4267             }
4268         }
4269     );
4270     $builder->build(
4271         {
4272             source => 'CirculationRule',
4273             value  => {
4274                 branchcode   => undef,
4275                 categorycode => undef,
4276                 itemtype     => undef,
4277                 rule_name    => 'lostreturn',
4278                 rule_value   => 'refund'
4279             }
4280         }
4281     );
4282
4283     subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
4284         plan tests => 3;
4285
4286         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
4287         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
4288
4289         my $lost_on = dt_from_string->subtract( days => 7 )->date;
4290
4291         my $item = $builder->build_sample_item(
4292             {
4293                 biblionumber     => $biblionumber,
4294                 library          => $library->branchcode,
4295                 replacementprice => '42',
4296             }
4297         );
4298         my $issue = AddIssue( $patron->unblessed, $item->barcode );
4299         LostItem( $item->itemnumber, 'cli', 0 );
4300         $item->_result->itemlost(1);
4301         $item->_result->itemlost_on( $lost_on );
4302         $item->_result->update();
4303
4304         my $a = Koha::Account::Lines->search(
4305             {
4306                 itemnumber     => $item->id,
4307                 borrowernumber => $patron->borrowernumber
4308             }
4309         )->next;
4310         ok( $a, "Found accountline for lost fee" );
4311         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4312         my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4313         $a = $a->get_from_storage;
4314         is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4315         $a->delete;
4316     };
4317
4318     subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
4319         plan tests => 3;
4320
4321         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
4322         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4323
4324         my $lost_on = dt_from_string->subtract( days => 6 )->date;
4325
4326         my $item = $builder->build_sample_item(
4327             {
4328                 biblionumber     => $biblionumber,
4329                 library          => $library->branchcode,
4330                 replacementprice => '42',
4331             }
4332         );
4333         my $issue = AddIssue( $patron->unblessed, $item->barcode );
4334         LostItem( $item->itemnumber, 'cli', 0 );
4335         $item->_result->itemlost(1);
4336         $item->_result->itemlost_on( $lost_on );
4337         $item->_result->update();
4338
4339         my $a = Koha::Account::Lines->search(
4340             {
4341                 itemnumber     => $item->id,
4342                 borrowernumber => $patron->borrowernumber
4343             }
4344         )->next;
4345         ok( $a, "Found accountline for lost fee" );
4346         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4347         my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4348         $a = $a->get_from_storage;
4349         is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4350         $a->delete;
4351     };
4352
4353     subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
4354         plan tests => 3;
4355
4356         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
4357         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4358
4359         my $lost_on = dt_from_string->subtract( days => 7 )->date;
4360
4361         my $item = $builder->build_sample_item(
4362             {
4363                 biblionumber     => $biblionumber,
4364                 library          => $library->branchcode,
4365                 replacementprice => '42',
4366             }
4367         );
4368         my $issue = AddIssue( $patron->unblessed, $item->barcode );
4369         LostItem( $item->itemnumber, 'cli', 0 );
4370         $item->_result->itemlost(1);
4371         $item->_result->itemlost_on( $lost_on );
4372         $item->_result->update();
4373
4374         my $a = Koha::Account::Lines->search(
4375             {
4376                 itemnumber     => $item->id,
4377                 borrowernumber => $patron->borrowernumber
4378             }
4379         )->next;
4380         ok( $a, "Found accountline for lost fee" );
4381         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4382         my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4383         $a = $a->get_from_storage;
4384         is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4385         $a->delete;
4386     };
4387
4388     subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
4389         plan tests => 3;
4390
4391         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
4392         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4393
4394         my $lost_on = dt_from_string->subtract( days => 8 )->date;
4395
4396         my $item = $builder->build_sample_item(
4397             {
4398                 biblionumber     => $biblionumber,
4399                 library          => $library->branchcode,
4400                 replacementprice => '42',
4401             }
4402         );
4403         my $issue = AddIssue( $patron->unblessed, $item->barcode );
4404         LostItem( $item->itemnumber, 'cli', 0 );
4405         $item->_result->itemlost(1);
4406         $item->_result->itemlost_on( $lost_on );
4407         $item->_result->update();
4408
4409         my $a = Koha::Account::Lines->search(
4410             {
4411                 itemnumber     => $item->id,
4412                 borrowernumber => $patron->borrowernumber
4413             }
4414         );
4415         $a = $a->next;
4416         ok( $a, "Found accountline for lost fee" );
4417         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4418         my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4419         $a = $a->get_from_storage;
4420         is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4421         $a->delete;
4422     };
4423 };
4424
4425 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub {
4426
4427     plan tests => 4;
4428
4429     t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
4430     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
4431     my $patron  = $builder->build_object(
4432         {
4433             class => 'Koha::Patrons',
4434             value => { categorycode => $patron_category->{categorycode} }
4435         }
4436     );
4437     my $patron2  = $builder->build_object(
4438         {
4439             class => 'Koha::Patrons',
4440             value => { categorycode => $patron_category->{categorycode} }
4441         }
4442     );
4443
4444     my $biblionumber = $builder->build_sample_biblio(
4445         {
4446             branchcode => $library->branchcode,
4447         }
4448     )->biblionumber;
4449
4450     # And the circulation rule
4451     Koha::CirculationRules->search->delete;
4452     Koha::CirculationRules->set_rules(
4453         {
4454             categorycode => undef,
4455             itemtype     => undef,
4456             branchcode   => undef,
4457             rules        => {
4458                 issuelength => 14,
4459                 lengthunit  => 'days',
4460             }
4461         }
4462     );
4463     $builder->build(
4464         {
4465             source => 'CirculationRule',
4466             value  => {
4467                 branchcode   => undef,
4468                 categorycode => undef,
4469                 itemtype     => undef,
4470                 rule_name    => 'lostreturn',
4471                 rule_value   => 'refund'
4472             }
4473         }
4474     );
4475
4476     subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
4477         plan tests => 3;
4478
4479         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
4480         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
4481
4482         my $lost_on = dt_from_string->subtract( days => 7 )->date;
4483
4484         my $item = $builder->build_sample_item(
4485             {
4486                 biblionumber     => $biblionumber,
4487                 library          => $library->branchcode,
4488                 replacementprice => '42',
4489             }
4490         );
4491         my $issue = AddIssue( $patron->unblessed, $item->barcode );
4492         LostItem( $item->itemnumber, 'cli', 0 );
4493         $item->_result->itemlost(1);
4494         $item->_result->itemlost_on( $lost_on );
4495         $item->_result->update();
4496
4497         my $a = Koha::Account::Lines->search(
4498             {
4499                 itemnumber     => $item->id,
4500                 borrowernumber => $patron->borrowernumber
4501             }
4502         )->next;
4503         ok( $a, "Found accountline for lost fee" );
4504         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4505         $issue = AddIssue( $patron2->unblessed, $item->barcode );
4506         $a = $a->get_from_storage;
4507         is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4508         $a->delete;
4509         $issue->delete;
4510     };
4511
4512     subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
4513         plan tests => 3;
4514
4515         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
4516         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4517
4518         my $lost_on = dt_from_string->subtract( days => 6 )->date;
4519
4520         my $item = $builder->build_sample_item(
4521             {
4522                 biblionumber     => $biblionumber,
4523                 library          => $library->branchcode,
4524                 replacementprice => '42',
4525             }
4526         );
4527         my $issue = AddIssue( $patron->unblessed, $item->barcode );
4528         LostItem( $item->itemnumber, 'cli', 0 );
4529         $item->_result->itemlost(1);
4530         $item->_result->itemlost_on( $lost_on );
4531         $item->_result->update();
4532
4533         my $a = Koha::Account::Lines->search(
4534             {
4535                 itemnumber     => $item->id,
4536                 borrowernumber => $patron->borrowernumber
4537             }
4538         )->next;
4539         ok( $a, "Found accountline for lost fee" );
4540         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4541         $issue = AddIssue( $patron2->unblessed, $item->barcode );
4542         $a = $a->get_from_storage;
4543         is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4544         $a->delete;
4545     };
4546
4547     subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
4548         plan tests => 3;
4549
4550         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
4551         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4552
4553         my $lost_on = dt_from_string->subtract( days => 7 )->date;
4554
4555         my $item = $builder->build_sample_item(
4556             {
4557                 biblionumber     => $biblionumber,
4558                 library          => $library->branchcode,
4559                 replacementprice => '42',
4560             }
4561         );
4562         my $issue = AddIssue( $patron->unblessed, $item->barcode );
4563         LostItem( $item->itemnumber, 'cli', 0 );
4564         $item->_result->itemlost(1);
4565         $item->_result->itemlost_on( $lost_on );
4566         $item->_result->update();
4567
4568         my $a = Koha::Account::Lines->search(
4569             {
4570                 itemnumber     => $item->id,
4571                 borrowernumber => $patron->borrowernumber
4572             }
4573         )->next;
4574         ok( $a, "Found accountline for lost fee" );
4575         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4576         $issue = AddIssue( $patron2->unblessed, $item->barcode );
4577         $a = $a->get_from_storage;
4578         is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4579         $a->delete;
4580     };
4581
4582     subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
4583         plan tests => 3;
4584
4585         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
4586         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4587
4588         my $lost_on = dt_from_string->subtract( days => 8 )->date;
4589
4590         my $item = $builder->build_sample_item(
4591             {
4592                 biblionumber     => $biblionumber,
4593                 library          => $library->branchcode,
4594                 replacementprice => '42',
4595             }
4596         );
4597         my $issue = AddIssue( $patron->unblessed, $item->barcode );
4598         LostItem( $item->itemnumber, 'cli', 0 );
4599         $item->_result->itemlost(1);
4600         $item->_result->itemlost_on( $lost_on );
4601         $item->_result->update();
4602
4603         my $a = Koha::Account::Lines->search(
4604             {
4605                 itemnumber     => $item->id,
4606                 borrowernumber => $patron->borrowernumber
4607             }
4608         );
4609         $a = $a->next;
4610         ok( $a, "Found accountline for lost fee" );
4611         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4612         $issue = AddIssue( $patron2->unblessed, $item->barcode );
4613         $a = $a->get_from_storage;
4614         is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4615         $a->delete;
4616     };
4617 };
4618
4619 subtest 'transferbook tests' => sub {
4620     plan tests => 9;
4621
4622     throws_ok
4623     { C4::Circulation::transferbook({}); }
4624     'Koha::Exceptions::MissingParameter',
4625     'Koha::Patron->store raises an exception on missing params';
4626
4627     throws_ok
4628     { C4::Circulation::transferbook({to_branch=>'anything'}); }
4629     'Koha::Exceptions::MissingParameter',
4630     'Koha::Patron->store raises an exception on missing params';
4631
4632     throws_ok
4633     { C4::Circulation::transferbook({from_branch=>'anything'}); }
4634     'Koha::Exceptions::MissingParameter',
4635     'Koha::Patron->store raises an exception on missing params';
4636
4637     my ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here'});
4638     is( $doreturn, 0, "No return without barcode");
4639     ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
4640     is( $messages->{BadBarcode}, undef, "No barcode passed means undef BadBarcode" );
4641
4642     ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here',barcode=>'BadBarcode'});
4643     is( $doreturn, 0, "No return without barcode");
4644     ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
4645     is( $messages->{BadBarcode}, 'BadBarcode', "No barcode passed means undef BadBarcode" );
4646
4647 };
4648
4649 subtest 'Checkout should correctly terminate a transfer' => sub {
4650     plan tests => 7;
4651
4652     my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
4653     my $patron_1 = $builder->build_object(
4654         {
4655             class => 'Koha::Patrons',
4656             value => { branchcode => $library_1->branchcode }
4657         }
4658     );
4659     my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } );
4660     my $patron_2 = $builder->build_object(
4661         {
4662             class => 'Koha::Patrons',
4663             value => { branchcode => $library_2->branchcode }
4664         }
4665     );
4666
4667     my $item = $builder->build_sample_item(
4668         {
4669             library => $library_1->branchcode,
4670         }
4671     );
4672
4673     t::lib::Mocks::mock_userenv( { branchcode => $library_1->branchcode } );
4674     my $reserve_id = AddReserve(
4675         {
4676             branchcode     => $library_2->branchcode,
4677             borrowernumber => $patron_2->borrowernumber,
4678             biblionumber   => $item->biblionumber,
4679             itemnumber     => $item->itemnumber,
4680             priority       => 1,
4681         }
4682     );
4683
4684     my $do_transfer = 1;
4685     ModItemTransfer( $item->itemnumber, $library_1->branchcode,
4686         $library_2->branchcode, 'Manual' );
4687     ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
4688     GetOtherReserves( $item->itemnumber )
4689       ;    # To put the Reason, it's what does returns.pl...
4690     my $hold = Koha::Holds->find($reserve_id);
4691     is( $hold->found, 'T', 'Hold is in transit' );
4692     my $transfer = $item->get_transfer;
4693     is( $transfer->frombranch, $library_1->branchcode );
4694     is( $transfer->tobranch,   $library_2->branchcode );
4695     is( $transfer->reason,     'Reserve' );
4696
4697     t::lib::Mocks::mock_userenv( { branchcode => $library_2->branchcode } );
4698     AddIssue( $patron_1->unblessed, $item->barcode );
4699     $transfer = $transfer->get_from_storage;
4700     isnt( $transfer->datearrived, undef );
4701     $hold = $hold->get_from_storage;
4702     is( $hold->found, undef, 'Hold is waiting' );
4703     is( $hold->priority, 1, );
4704 };
4705
4706 subtest 'AddIssue records staff who checked out item if appropriate' => sub  {
4707     plan tests => 2;
4708
4709     $module->mock( 'userenv', sub { { branch => $library->{id} } } );
4710
4711     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
4712     my $patron = $builder->build_object(
4713         {
4714             class => 'Koha::Patrons',
4715             value => { categorycode => $patron_category->{categorycode} }
4716         }
4717     );
4718     my $issuer = $builder->build_object(
4719         {
4720             class => 'Koha::Patrons',
4721             value => { categorycode => $patron_category->{categorycode} }
4722         }
4723     );
4724     my $item = $builder->build_sample_item(
4725         {
4726             library  => $library->{branchcode}
4727         }
4728     );
4729
4730     $module->mock( 'userenv', sub { { branch => $library->id, number => $issuer->{borrowernumber} } } );
4731
4732     my $dt_from = dt_from_string();
4733     my $dt_to   = dt_from_string()->add( days => 7 );
4734
4735     my $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4736
4737     is( $issue->issuer, undef, "Staff who checked out the item not recorded when RecordStaffUserOnCheckout turned off" );
4738
4739     t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 1);
4740
4741     my $issue2 =
4742       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4743
4744     is( $issue->issuer, $issuer->{borrowernumber}, "Staff who checked out the item recorded when RecordStaffUserOnCheckout turned on" );
4745 };
4746
4747 subtest "Item's onloan value should be set if checked out item is checked out to a different patron" => sub {
4748     plan tests => 2;
4749
4750     my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
4751     my $patron_1 = $builder->build_object(
4752         {
4753             class => 'Koha::Patrons',
4754             value => { branchcode => $library_1->branchcode }
4755         }
4756     );
4757     my $patron_2 = $builder->build_object(
4758         {
4759             class => 'Koha::Patrons',
4760             value => { branchcode => $library_1->branchcode }
4761         }
4762     );
4763
4764     my $item = $builder->build_sample_item(
4765         {
4766             library => $library_1->branchcode,
4767         }
4768     );
4769
4770     AddIssue( $patron_1->unblessed, $item->barcode );
4771     ok( $item->get_from_storage->onloan, "Item's onloan column is set after initial checkout" );
4772     AddIssue( $patron_2->unblessed, $item->barcode );
4773     ok( $item->get_from_storage->onloan, "Item's onloan column is set after second checkout" );
4774 };
4775
4776 $schema->storage->txn_rollback;
4777 C4::Context->clear_syspref_cache();
4778 $branches = Koha::Libraries->search();
4779 for my $branch ( $branches->next ) {
4780     my $key = $branch->branchcode . "_holidays";
4781     $cache->clear_from_cache($key);
4782 }