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