Bug 23695: (follow-up) Add exceptions for missing branch parameters
[koha.git] / t / db_dependent / Circulation.t
blobbf729494d4762e45d347e8665b50a09c506deb3c
1 #!/usr/bin/perl
3 # This file is part of Koha.
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.
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.
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>.
18 use Modern::Perl;
19 use utf8;
21 use Test::More tests => 50;
22 use Test::Exception;
23 use Test::MockModule;
24 use Test::Deep qw( cmp_deeply );
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;
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;
54 sub set_userenv {
55 my ( $library ) = @_;
56 t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
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;
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};
77 $expected_expiration_date = output_pref(
79 dt => $expected_expiration_date,
80 dateformat => 'sql',
81 dateonly => 1,
84 my @caller = caller;
85 my $line_number = $caller[2];
86 AddIssue( $patron, $item->{barcode}, $due_date );
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 );
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' } );
101 my $schema = Koha::Database->schema;
102 $schema->storage->txn_begin;
103 my $builder = t::lib::TestBuilder->new;
104 my $dbh = C4::Context->dbh;
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; } );
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);
120 # Start with a clean slate
121 $dbh->do('DELETE FROM issues');
122 $dbh->do('DELETE FROM borrowers');
124 my $library = $builder->build({
125 source => 'Branch',
127 my $library2 = $builder->build({
128 source => 'Branch',
130 my $itemtype = $builder->build(
132 source => 'Itemtype',
133 value => {
134 notforloan => undef,
135 rentalcharge => 0,
136 rentalcharge_daily => 0,
137 defaultreplacecost => undef,
138 processfee => undef
141 )->{itemtype};
142 my $patron_category = $builder->build(
144 source => 'Category',
145 value => {
146 category_type => 'P',
147 enrolmentfee => 0,
148 BlockExpiredPatronOpacActions => -1, # Pick the pref value
153 my $CircControl = C4::Context->preference('CircControl');
154 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
156 my $item = {
157 homebranch => $library2->{branchcode},
158 holdingbranch => $library2->{branchcode}
161 my $borrower = {
162 branchcode => $library2->{branchcode}
165 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
167 # No userenv, PickupLibrary
168 t::lib::Mocks::mock_preference('IndependentBranches', '0');
169 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
171 C4::Context->preference('CircControl'),
172 'PickupLibrary',
173 'CircControl changed to PickupLibrary'
176 C4::Circulation::_GetCircControlBranch($item, $borrower),
177 $item->{$HomeOrHoldingBranch},
178 '_GetCircControlBranch returned item branch (no userenv defined)'
181 # No userenv, PatronLibrary
182 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
184 C4::Context->preference('CircControl'),
185 'PatronLibrary',
186 'CircControl changed to PatronLibrary'
189 C4::Circulation::_GetCircControlBranch($item, $borrower),
190 $borrower->{branchcode},
191 '_GetCircControlBranch returned borrower branch'
194 # No userenv, ItemHomeLibrary
195 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
197 C4::Context->preference('CircControl'),
198 'ItemHomeLibrary',
199 'CircControl changed to ItemHomeLibrary'
202 $item->{$HomeOrHoldingBranch},
203 C4::Circulation::_GetCircControlBranch($item, $borrower),
204 '_GetCircControlBranch returned item branch'
207 # Now, set a userenv
208 t::lib::Mocks::mock_userenv({ branchcode => $library2->{branchcode} });
209 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
211 # Userenv set, PickupLibrary
212 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
214 C4::Context->preference('CircControl'),
215 'PickupLibrary',
216 'CircControl changed to PickupLibrary'
219 C4::Circulation::_GetCircControlBranch($item, $borrower),
220 $library2->{branchcode},
221 '_GetCircControlBranch returned current branch'
224 # Userenv set, PatronLibrary
225 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
227 C4::Context->preference('CircControl'),
228 'PatronLibrary',
229 'CircControl changed to PatronLibrary'
232 C4::Circulation::_GetCircControlBranch($item, $borrower),
233 $borrower->{branchcode},
234 '_GetCircControlBranch returned borrower branch'
237 # Userenv set, ItemHomeLibrary
238 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
240 C4::Context->preference('CircControl'),
241 'ItemHomeLibrary',
242 'CircControl changed to ItemHomeLibrary'
245 C4::Circulation::_GetCircControlBranch($item, $borrower),
246 $item->{$HomeOrHoldingBranch},
247 '_GetCircControlBranch returned item branch'
250 # Reset initial configuration
251 t::lib::Mocks::mock_preference('CircControl', $CircControl);
253 C4::Context->preference('CircControl'),
254 $CircControl,
255 'CircControl reset to its initial value'
258 # Set a simple circ policy
259 $dbh->do('DELETE FROM circulation_rules');
260 Koha::CirculationRules->set_rules(
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,
279 my ( $reused_itemnumber_1, $reused_itemnumber_2 );
280 subtest "CanBookBeRenewed tests" => sub {
281 plan tests => 83;
283 C4::Context->set_preference('ItemsDeniedRenewal','');
284 # Generate test biblio
285 my $biblio = $builder->build_sample_biblio();
287 my $branch = $library2->{branchcode};
289 my $item_1 = $builder->build_sample_item(
291 biblionumber => $biblio->biblionumber,
292 library => $branch,
293 replacementprice => 12.00,
294 itype => $itemtype
297 $reused_itemnumber_1 = $item_1->itemnumber;
299 my $item_2 = $builder->build_sample_item(
301 biblionumber => $biblio->biblionumber,
302 library => $branch,
303 replacementprice => 23.00,
304 itype => $itemtype
307 $reused_itemnumber_2 = $item_2->itemnumber;
309 my $item_3 = $builder->build_sample_item(
311 biblionumber => $biblio->biblionumber,
312 library => $branch,
313 replacementprice => 23.00,
314 itype => $itemtype
318 # Create borrowers
319 my %renewing_borrower_data = (
320 firstname => 'John',
321 surname => 'Renewal',
322 categorycode => $patron_category->{categorycode},
323 branchcode => $branch,
326 my %reserving_borrower_data = (
327 firstname => 'Katrin',
328 surname => 'Reservation',
329 categorycode => $patron_category->{categorycode},
330 branchcode => $branch,
333 my %hold_waiting_borrower_data = (
334 firstname => 'Kyle',
335 surname => 'Reservation',
336 categorycode => $patron_category->{categorycode},
337 branchcode => $branch,
340 my %restricted_borrower_data = (
341 firstname => 'Alice',
342 surname => 'Reservation',
343 categorycode => $patron_category->{categorycode},
344 debarred => '3228-01-01',
345 branchcode => $branch,
348 my %expired_borrower_data = (
349 firstname => 'Ça',
350 surname => 'Glisse',
351 categorycode => $patron_category->{categorycode},
352 branchcode => $branch,
353 dateexpiry => dt_from_string->subtract( months => 1 ),
356 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
357 my $reserving_borrowernumber = Koha::Patron->new(\%reserving_borrower_data)->store->borrowernumber;
358 my $hold_waiting_borrowernumber = Koha::Patron->new(\%hold_waiting_borrower_data)->store->borrowernumber;
359 my $restricted_borrowernumber = Koha::Patron->new(\%restricted_borrower_data)->store->borrowernumber;
360 my $expired_borrowernumber = Koha::Patron->new(\%expired_borrower_data)->store->borrowernumber;
362 my $renewing_borrower_obj = Koha::Patrons->find( $renewing_borrowernumber );
363 my $renewing_borrower = $renewing_borrower_obj->unblessed;
364 my $restricted_borrower = Koha::Patrons->find( $restricted_borrowernumber )->unblessed;
365 my $expired_borrower = Koha::Patrons->find( $expired_borrowernumber )->unblessed;
367 my $bibitems = '';
368 my $priority = '1';
369 my $resdate = undef;
370 my $expdate = undef;
371 my $notes = '';
372 my $checkitem = undef;
373 my $found = undef;
375 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
376 my $datedue = dt_from_string( $issue->date_due() );
377 is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
379 my $issue2 = AddIssue( $renewing_borrower, $item_2->barcode);
380 $datedue = dt_from_string( $issue->date_due() );
381 is (defined $issue2, 1, "Item 2 checked out, due date: " . $issue2->date_due());
384 my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $item_1->itemnumber } )->borrowernumber;
385 is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
387 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
388 is( $renewokay, 1, 'Can renew, no holds for this title or item');
391 # Biblio-level hold, renewal test
392 AddReserve(
394 branchcode => $branch,
395 borrowernumber => $reserving_borrowernumber,
396 biblionumber => $biblio->biblionumber,
397 priority => $priority,
398 reservation_date => $resdate,
399 expiration_date => $expdate,
400 notes => $notes,
401 itemnumber => $checkitem,
402 found => $found,
406 # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
407 Koha::CirculationRules->set_rule(
409 categorycode => undef,
410 branchcode => undef,
411 itemtype => undef,
412 rule_name => 'onshelfholds',
413 rule_value => '1',
416 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
417 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
418 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
419 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
420 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
422 # Now let's add an item level hold, we should no longer be able to renew the item
423 my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
425 borrowernumber => $hold_waiting_borrowernumber,
426 biblionumber => $biblio->biblionumber,
427 itemnumber => $item_1->itemnumber,
428 branchcode => $branch,
429 priority => 3,
432 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
433 is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
434 $hold->delete();
436 # 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
437 # be able to renew these items
438 $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
440 borrowernumber => $hold_waiting_borrowernumber,
441 biblionumber => $biblio->biblionumber,
442 itemnumber => $item_3->itemnumber,
443 branchcode => $branch,
444 priority => 0,
445 found => 'W'
448 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
449 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
450 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
451 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
452 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
454 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
455 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
456 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
458 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
459 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
460 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
462 my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
463 my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber )->unblessed;
464 AddIssue($reserving_borrower, $item_3->barcode);
465 my $reserve = $dbh->selectrow_hashref(
466 'SELECT * FROM old_reserves WHERE reserve_id = ?',
467 { Slice => {} },
468 $reserveid
470 is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
472 # Item-level hold, renewal test
473 AddReserve(
475 branchcode => $branch,
476 borrowernumber => $reserving_borrowernumber,
477 biblionumber => $biblio->biblionumber,
478 priority => $priority,
479 reservation_date => $resdate,
480 expiration_date => $expdate,
481 notes => $notes,
482 itemnumber => $item_1->itemnumber,
483 found => $found,
487 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
488 is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
489 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
491 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber, 1);
492 is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
494 # Items can't fill hold for reasons
495 $item_1->notforloan(1)->store;
496 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
497 is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
498 $item_1->set({notforloan => 0, itype => $itemtype })->store;
500 # FIXME: Add more for itemtype not for loan etc.
502 # Restricted users cannot renew when RestrictionBlockRenewing is enabled
503 my $item_5 = $builder->build_sample_item(
505 biblionumber => $biblio->biblionumber,
506 library => $branch,
507 replacementprice => 23.00,
508 itype => $itemtype,
511 my $datedue5 = AddIssue($restricted_borrower, $item_5->barcode);
512 is (defined $datedue5, 1, "Item with date due checked out, due date: $datedue5");
514 t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
515 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
516 is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
517 ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrowernumber, $item_5->itemnumber);
518 is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
520 # Users cannot renew an overdue item
521 my $item_6 = $builder->build_sample_item(
523 biblionumber => $biblio->biblionumber,
524 library => $branch,
525 replacementprice => 23.00,
526 itype => $itemtype,
530 my $item_7 = $builder->build_sample_item(
532 biblionumber => $biblio->biblionumber,
533 library => $branch,
534 replacementprice => 23.00,
535 itype => $itemtype,
539 my $datedue6 = AddIssue( $renewing_borrower, $item_6->barcode);
540 is (defined $datedue6, 1, "Item 2 checked out, due date: ".$datedue6->date_due);
542 my $now = dt_from_string();
543 my $five_weeks = DateTime::Duration->new(weeks => 5);
544 my $five_weeks_ago = $now - $five_weeks;
545 t::lib::Mocks::mock_preference('finesMode', 'production');
547 my $passeddatedue1 = AddIssue($renewing_borrower, $item_7->barcode, $five_weeks_ago);
548 is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: " . $passeddatedue1->date_due);
550 my ( $fine ) = CalcFine( $item_7->unblessed, $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
551 C4::Overdues::UpdateFine(
553 issue_id => $passeddatedue1->id(),
554 itemnumber => $item_7->itemnumber,
555 borrowernumber => $renewing_borrower->{borrowernumber},
556 amount => $fine,
557 due => Koha::DateUtils::output_pref($five_weeks_ago)
561 t::lib::Mocks::mock_preference('RenewalLog', 0);
562 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
563 my %params_renewal = (
564 timestamp => { -like => $date . "%" },
565 module => "CIRCULATION",
566 action => "RENEWAL",
568 my %params_issue = (
569 timestamp => { -like => $date . "%" },
570 module => "CIRCULATION",
571 action => "ISSUE"
573 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );
574 my $dt = dt_from_string();
575 Time::Fake->offset( $dt->epoch );
576 my $datedue1 = AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
577 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
578 is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
579 isnt (DateTime->compare($datedue1, $dt), 0, "AddRenewal returned a good duedate");
580 Time::Fake->reset;
582 t::lib::Mocks::mock_preference('RenewalLog', 1);
583 $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
584 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
585 AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
586 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
587 is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
589 my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
590 is( $fines->count, 2, 'AddRenewal left both fines' );
591 isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
592 isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
593 $fines->delete();
596 my $old_issue_log_size = Koha::ActionLogs->count( \%params_issue );
597 my $old_renew_log_size = Koha::ActionLogs->count( \%params_renewal );
598 AddIssue( $renewing_borrower,$item_7->barcode,Koha::DateUtils::output_pref({str=>$datedue6->date_due, dateformat =>'iso'}),0,$date, 0, undef );
599 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
600 is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
601 $new_log_size = Koha::ActionLogs->count( \%params_issue );
602 is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
604 $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
605 $fines->delete();
607 t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
608 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
609 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
610 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
611 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
614 $hold = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next;
615 $hold->cancel;
617 # Bug 14101
618 # Test automatic renewal before value for "norenewalbefore" in policy is set
619 # In this case automatic renewal is not permitted prior to due date
620 my $item_4 = $builder->build_sample_item(
622 biblionumber => $biblio->biblionumber,
623 library => $branch,
624 replacementprice => 16.00,
625 itype => $itemtype,
629 $issue = AddIssue( $renewing_borrower, $item_4->barcode, undef, undef, undef, undef, { auto_renew => 1 } );
630 ( $renewokay, $error ) =
631 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
632 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
633 is( $error, 'auto_too_soon',
634 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
635 AddReserve(
637 branchcode => $branch,
638 borrowernumber => $reserving_borrowernumber,
639 biblionumber => $biblio->biblionumber,
640 itemnumber => $bibitems,
641 priority => $priority,
642 reservation_date => $resdate,
643 expiration_date => $expdate,
644 notes => $notes,
645 title => 'a title',
646 itemnumber => $item_4->itemnumber,
647 found => $found
650 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
651 is( $renewokay, 0, 'Still should not be able to renew' );
652 is( $error, 'auto_too_soon', 'returned code is auto_too_soon, reserve not checked' );
653 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
654 is( $renewokay, 0, 'Still should not be able to renew' );
655 is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
656 $dbh->do('UPDATE circulation_rules SET rule_value = 0 where rule_name = "norenewalbefore"');
657 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
658 is( $renewokay, 0, 'Still should not be able to renew' );
659 is( $error, 'on_reserve', 'returned code is on_reserve, auto_renew only happens if not on reserve' );
660 ModReserveCancelAll($item_4->itemnumber, $reserving_borrowernumber);
664 $renewing_borrower_obj->autorenew_checkouts(0)->store;
665 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
666 is( $renewokay, 1, 'No renewal before is undef, but patron opted out of auto_renewal' );
667 $renewing_borrower_obj->autorenew_checkouts(1)->store;
670 # Bug 7413
671 # Test premature manual renewal
672 Koha::CirculationRules->set_rule(
674 categorycode => undef,
675 branchcode => undef,
676 itemtype => undef,
677 rule_name => 'norenewalbefore',
678 rule_value => '7',
682 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
683 is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
684 is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
686 # Bug 14395
687 # Test 'exact time' setting for syspref NoRenewalBeforePrecision
688 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
690 GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
691 $datedue->clone->add( days => -7 ),
692 'Bug 14395: Renewals permitted 7 days before due date, as expected'
695 # Bug 14395
696 # Test 'date' setting for syspref NoRenewalBeforePrecision
697 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
699 GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
700 $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
701 'Bug 14395: Renewals permitted 7 days before due date, as expected'
704 # Bug 14101
705 # Test premature automatic renewal
706 ( $renewokay, $error ) =
707 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
708 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
709 is( $error, 'auto_too_soon',
710 'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
713 $renewing_borrower_obj->autorenew_checkouts(0)->store;
714 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
715 is( $renewokay, 0, 'No renewal before is 7, patron opted out of auto_renewal still cannot renew early' );
716 is( $error, 'too_soon', 'Error is too_soon, no auto' );
717 $renewing_borrower_obj->autorenew_checkouts(1)->store;
719 # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
720 # and test automatic renewal again
721 $dbh->do(q{UPDATE circulation_rules SET rule_value = '0' WHERE rule_name = 'norenewalbefore'});
722 ( $renewokay, $error ) =
723 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
724 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
725 is( $error, 'auto_too_soon',
726 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
729 $renewing_borrower_obj->autorenew_checkouts(0)->store;
730 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
731 is( $renewokay, 0, 'No renewal before is 0, patron opted out of auto_renewal still cannot renew early' );
732 is( $error, 'too_soon', 'Error is too_soon, no auto' );
733 $renewing_borrower_obj->autorenew_checkouts(1)->store;
735 # Change policy so that loans can be renewed 99 days prior to the due date
736 # and test automatic renewal again
737 $dbh->do(q{UPDATE circulation_rules SET rule_value = '99' WHERE rule_name = 'norenewalbefore'});
738 ( $renewokay, $error ) =
739 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
740 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
741 is( $error, 'auto_renew',
742 'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
745 $renewing_borrower_obj->autorenew_checkouts(0)->store;
746 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
747 is( $renewokay, 1, 'No renewal before is 99, patron opted out of auto_renewal so can renew' );
748 $renewing_borrower_obj->autorenew_checkouts(1)->store;
750 subtest "too_late_renewal / no_auto_renewal_after" => sub {
751 plan tests => 14;
752 my $item_to_auto_renew = $builder->build(
753 { source => 'Item',
754 value => {
755 biblionumber => $biblio->biblionumber,
756 homebranch => $branch,
757 holdingbranch => $branch,
762 my $ten_days_before = dt_from_string->add( days => -10 );
763 my $ten_days_ahead = dt_from_string->add( days => 10 );
764 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
766 Koha::CirculationRules->set_rules(
768 categorycode => undef,
769 branchcode => undef,
770 itemtype => undef,
771 rules => {
772 norenewalbefore => '7',
773 no_auto_renewal_after => '9',
777 ( $renewokay, $error ) =
778 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
779 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
780 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
782 Koha::CirculationRules->set_rules(
784 categorycode => undef,
785 branchcode => undef,
786 itemtype => undef,
787 rules => {
788 norenewalbefore => '7',
789 no_auto_renewal_after => '10',
793 ( $renewokay, $error ) =
794 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
795 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
796 is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
798 Koha::CirculationRules->set_rules(
800 categorycode => undef,
801 branchcode => undef,
802 itemtype => undef,
803 rules => {
804 norenewalbefore => '7',
805 no_auto_renewal_after => '11',
809 ( $renewokay, $error ) =
810 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
811 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
812 is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
814 Koha::CirculationRules->set_rules(
816 categorycode => undef,
817 branchcode => undef,
818 itemtype => undef,
819 rules => {
820 norenewalbefore => '10',
821 no_auto_renewal_after => '11',
825 ( $renewokay, $error ) =
826 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
827 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
828 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
830 Koha::CirculationRules->set_rules(
832 categorycode => undef,
833 branchcode => undef,
834 itemtype => undef,
835 rules => {
836 norenewalbefore => '10',
837 no_auto_renewal_after => undef,
838 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
842 ( $renewokay, $error ) =
843 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
844 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
845 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
847 Koha::CirculationRules->set_rules(
849 categorycode => undef,
850 branchcode => undef,
851 itemtype => undef,
852 rules => {
853 norenewalbefore => '7',
854 no_auto_renewal_after => '15',
855 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
859 ( $renewokay, $error ) =
860 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
861 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
862 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
864 Koha::CirculationRules->set_rules(
866 categorycode => undef,
867 branchcode => undef,
868 itemtype => undef,
869 rules => {
870 norenewalbefore => '10',
871 no_auto_renewal_after => undef,
872 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 1 ),
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' );
882 subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew & OPACFineNoRenewalsIncludeCredit" => sub {
883 plan tests => 10;
884 my $item_to_auto_renew = $builder->build({
885 source => 'Item',
886 value => {
887 biblionumber => $biblio->biblionumber,
888 homebranch => $branch,
889 holdingbranch => $branch,
893 my $ten_days_before = dt_from_string->add( days => -10 );
894 my $ten_days_ahead = dt_from_string->add( days => 10 );
895 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
897 Koha::CirculationRules->set_rules(
899 categorycode => undef,
900 branchcode => undef,
901 itemtype => undef,
902 rules => {
903 norenewalbefore => '10',
904 no_auto_renewal_after => '11',
908 C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
909 C4::Context->set_preference('OPACFineNoRenewals','10');
910 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
911 my $fines_amount = 5;
912 my $account = Koha::Account->new({patron_id => $renewing_borrowernumber});
913 $account->add_debit(
915 amount => $fines_amount,
916 interface => 'test',
917 type => 'OVERDUE',
918 item_id => $item_to_auto_renew->{itemnumber},
919 description => "Some fines"
921 )->status('RETURNED')->store;
922 ( $renewokay, $error ) =
923 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
924 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
925 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
927 $account->add_debit(
929 amount => $fines_amount,
930 interface => 'test',
931 type => 'OVERDUE',
932 item_id => $item_to_auto_renew->{itemnumber},
933 description => "Some fines"
935 )->status('RETURNED')->store;
936 ( $renewokay, $error ) =
937 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
938 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
939 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
941 $account->add_debit(
943 amount => $fines_amount,
944 interface => 'test',
945 type => 'OVERDUE',
946 item_id => $item_to_auto_renew->{itemnumber},
947 description => "Some fines"
949 )->status('RETURNED')->store;
950 ( $renewokay, $error ) =
951 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
952 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
953 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
955 $account->add_credit(
957 amount => $fines_amount,
958 interface => 'test',
959 type => 'PAYMENT',
960 description => "Some payment"
962 )->store;
963 ( $renewokay, $error ) =
964 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
965 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
966 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
968 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','0');
969 ( $renewokay, $error ) =
970 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
971 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
972 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
974 $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
975 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
978 subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
979 plan tests => 6;
980 my $item_to_auto_renew = $builder->build({
981 source => 'Item',
982 value => {
983 biblionumber => $biblio->biblionumber,
984 homebranch => $branch,
985 holdingbranch => $branch,
989 Koha::CirculationRules->set_rules(
991 categorycode => undef,
992 branchcode => undef,
993 itemtype => undef,
994 rules => {
995 norenewalbefore => 10,
996 no_auto_renewal_after => 11,
1001 my $ten_days_before = dt_from_string->add( days => -10 );
1002 my $ten_days_ahead = dt_from_string->add( days => 10 );
1004 # Patron is expired and BlockExpiredPatronOpacActions=0
1005 # => auto renew is allowed
1006 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
1007 my $patron = $expired_borrower;
1008 my $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1009 ( $renewokay, $error ) =
1010 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
1011 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1012 is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
1013 Koha::Checkouts->find( $checkout->issue_id )->delete;
1016 # Patron is expired and BlockExpiredPatronOpacActions=1
1017 # => auto renew is not allowed
1018 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1019 $patron = $expired_borrower;
1020 $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1021 ( $renewokay, $error ) =
1022 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
1023 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1024 is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
1025 Koha::Checkouts->find( $checkout->issue_id )->delete;
1028 # Patron is not expired and BlockExpiredPatronOpacActions=1
1029 # => auto renew is allowed
1030 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1031 $patron = $renewing_borrower;
1032 $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1033 ( $renewokay, $error ) =
1034 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
1035 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1036 is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
1037 Koha::Checkouts->find( $checkout->issue_id )->delete;
1040 subtest "GetLatestAutoRenewDate" => sub {
1041 plan tests => 5;
1042 my $item_to_auto_renew = $builder->build(
1043 { source => 'Item',
1044 value => {
1045 biblionumber => $biblio->biblionumber,
1046 homebranch => $branch,
1047 holdingbranch => $branch,
1052 my $ten_days_before = dt_from_string->add( days => -10 );
1053 my $ten_days_ahead = dt_from_string->add( days => 10 );
1054 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1055 Koha::CirculationRules->set_rules(
1057 categorycode => undef,
1058 branchcode => undef,
1059 itemtype => undef,
1060 rules => {
1061 norenewalbefore => '7',
1062 no_auto_renewal_after => '',
1063 no_auto_renewal_after_hard_limit => undef,
1067 my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1068 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' );
1069 my $five_days_before = dt_from_string->add( days => -5 );
1070 Koha::CirculationRules->set_rules(
1072 categorycode => undef,
1073 branchcode => undef,
1074 itemtype => undef,
1075 rules => {
1076 norenewalbefore => '10',
1077 no_auto_renewal_after => '5',
1078 no_auto_renewal_after_hard_limit => undef,
1082 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1083 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1084 $five_days_before->truncate( to => 'minute' ),
1085 'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
1087 my $five_days_ahead = dt_from_string->add( days => 5 );
1088 $dbh->do(q{UPDATE circulation_rules SET rule_value = '10' WHERE rule_name = 'norenewalbefore'});
1089 $dbh->do(q{UPDATE circulation_rules SET rule_value = '15' WHERE rule_name = 'no_auto_renewal_after'});
1090 $dbh->do(q{UPDATE circulation_rules SET rule_value = NULL WHERE rule_name = 'no_auto_renewal_after_hard_limit'});
1091 Koha::CirculationRules->set_rules(
1093 categorycode => undef,
1094 branchcode => undef,
1095 itemtype => undef,
1096 rules => {
1097 norenewalbefore => '10',
1098 no_auto_renewal_after => '15',
1099 no_auto_renewal_after_hard_limit => undef,
1103 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1104 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1105 $five_days_ahead->truncate( to => 'minute' ),
1106 'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
1108 my $two_days_ahead = dt_from_string->add( days => 2 );
1109 Koha::CirculationRules->set_rules(
1111 categorycode => undef,
1112 branchcode => undef,
1113 itemtype => undef,
1114 rules => {
1115 norenewalbefore => '10',
1116 no_auto_renewal_after => '',
1117 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1121 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1122 is( $latest_auto_renew_date->truncate( to => 'day' ),
1123 $two_days_ahead->truncate( to => 'day' ),
1124 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
1126 Koha::CirculationRules->set_rules(
1128 categorycode => undef,
1129 branchcode => undef,
1130 itemtype => undef,
1131 rules => {
1132 norenewalbefore => '10',
1133 no_auto_renewal_after => '15',
1134 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1138 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1139 is( $latest_auto_renew_date->truncate( to => 'day' ),
1140 $two_days_ahead->truncate( to => 'day' ),
1141 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
1145 # Too many renewals
1147 # set policy to forbid renewals
1148 Koha::CirculationRules->set_rules(
1150 categorycode => undef,
1151 branchcode => undef,
1152 itemtype => undef,
1153 rules => {
1154 norenewalbefore => undef,
1155 renewalsallowed => 0,
1160 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
1161 is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
1162 is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
1164 # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
1165 t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
1166 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1168 C4::Overdues::UpdateFine(
1170 issue_id => $issue->id(),
1171 itemnumber => $item_1->itemnumber,
1172 borrowernumber => $renewing_borrower->{borrowernumber},
1173 amount => 15.00,
1174 type => q{},
1175 due => Koha::DateUtils::output_pref($datedue)
1179 my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower->{borrowernumber} })->next();
1180 is( $line->debit_type_code, 'OVERDUE', 'Account line type is OVERDUE' );
1181 is( $line->status, 'UNRETURNED', 'Account line status is UNRETURNED' );
1182 is( $line->amountoutstanding+0, 15, 'Account line amount outstanding is 15.00' );
1183 is( $line->amount+0, 15, 'Account line amount is 15.00' );
1184 is( $line->issue_id, $issue->id, 'Account line issue id matches' );
1186 my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
1187 is( $offset->type, 'OVERDUE', 'Account offset type is Fine' );
1188 is( $offset->amount+0, 15, 'Account offset amount is 15.00' );
1190 t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
1191 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
1193 LostItem( $item_1->itemnumber, 'test', 1 );
1195 $line = Koha::Account::Lines->find($line->id);
1196 is( $line->debit_type_code, 'OVERDUE', 'Account type remains as OVERDUE' );
1197 isnt( $line->status, 'UNRETURNED', 'Account status correctly changed from UNRETURNED to RETURNED' );
1199 my $item = Koha::Items->find($item_1->itemnumber);
1200 ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
1201 my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
1202 is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
1204 my $total_due = $dbh->selectrow_array(
1205 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1206 undef, $renewing_borrower->{borrowernumber}
1209 is( $total_due+0, 15, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
1211 C4::Context->dbh->do("DELETE FROM accountlines");
1213 C4::Overdues::UpdateFine(
1215 issue_id => $issue2->id(),
1216 itemnumber => $item_2->itemnumber,
1217 borrowernumber => $renewing_borrower->{borrowernumber},
1218 amount => 15.00,
1219 type => q{},
1220 due => Koha::DateUtils::output_pref($datedue)
1224 LostItem( $item_2->itemnumber, 'test', 0 );
1226 my $item2 = Koha::Items->find($item_2->itemnumber);
1227 ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
1228 ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
1230 $total_due = $dbh->selectrow_array(
1231 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1232 undef, $renewing_borrower->{borrowernumber}
1235 ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
1237 my $future = dt_from_string();
1238 $future->add( days => 7 );
1239 my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
1240 ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
1242 # Users cannot renew any item if there is an overdue item
1243 t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
1244 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
1245 is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
1246 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
1247 is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
1249 my $manager = $builder->build_object({ class => "Koha::Patrons" });
1250 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
1251 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1252 $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
1253 LostItem( $item_3->itemnumber, 'test', 0 );
1254 my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
1255 is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
1257 $accountline->description,
1258 sprintf( "%s %s %s",
1259 $item_3->biblio->title || '',
1260 $item_3->barcode || '',
1261 $item_3->itemcallnumber || '' ),
1262 "Account line description must not contain 'Lost Items ', but be title, barcode, itemcallnumber"
1266 subtest "GetUpcomingDueIssues" => sub {
1267 plan tests => 12;
1269 my $branch = $library2->{branchcode};
1271 #Create another record
1272 my $biblio2 = $builder->build_sample_biblio();
1274 #Create third item
1275 my $item_1 = Koha::Items->find($reused_itemnumber_1);
1276 my $item_2 = Koha::Items->find($reused_itemnumber_2);
1277 my $item_3 = $builder->build_sample_item(
1279 biblionumber => $biblio2->biblionumber,
1280 library => $branch,
1281 itype => $itemtype,
1286 # Create a borrower
1287 my %a_borrower_data = (
1288 firstname => 'Fridolyn',
1289 surname => 'SOMERS',
1290 categorycode => $patron_category->{categorycode},
1291 branchcode => $branch,
1294 my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1295 my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
1297 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
1298 my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
1299 my $today = DateTime->today(time_zone => C4::Context->tz());
1301 my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
1302 my $datedue = dt_from_string( $issue->date_due() );
1303 my $issue2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
1304 my $datedue2 = dt_from_string( $issue->date_due() );
1306 my $upcoming_dues;
1308 # GetUpcomingDueIssues tests
1309 for my $i(0..1) {
1310 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1311 is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
1314 #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
1315 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1316 is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
1318 for my $i(3..5) {
1319 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1320 is ( scalar( @$upcoming_dues ), 1,
1321 "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
1324 # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
1326 my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
1328 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
1329 is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
1331 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
1332 is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
1334 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
1335 is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
1337 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1338 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1340 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1341 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1343 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1344 is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1348 subtest "Bug 13841 - Do not create new 0 amount fines" => sub {
1349 my $branch = $library2->{branchcode};
1351 my $biblio = $builder->build_sample_biblio();
1353 #Create third item
1354 my $item = $builder->build_sample_item(
1356 biblionumber => $biblio->biblionumber,
1357 library => $branch,
1358 itype => $itemtype,
1362 # Create a borrower
1363 my %a_borrower_data = (
1364 firstname => 'Kyle',
1365 surname => 'Hall',
1366 categorycode => $patron_category->{categorycode},
1367 branchcode => $branch,
1370 my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1372 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1373 my $issue = AddIssue( $borrower, $item->barcode );
1374 UpdateFine(
1376 issue_id => $issue->id(),
1377 itemnumber => $item->itemnumber,
1378 borrowernumber => $borrowernumber,
1379 amount => 0,
1380 type => q{}
1384 my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1385 my $count = $hr->{count};
1387 is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1390 subtest "AllowRenewalIfOtherItemsAvailable tests" => sub {
1391 $dbh->do('DELETE FROM issues');
1392 $dbh->do('DELETE FROM items');
1393 $dbh->do('DELETE FROM circulation_rules');
1394 Koha::CirculationRules->set_rules(
1396 categorycode => undef,
1397 itemtype => undef,
1398 branchcode => undef,
1399 rules => {
1400 reservesallowed => 25,
1401 issuelength => 14,
1402 lengthunit => 'days',
1403 renewalsallowed => 1,
1404 renewalperiod => 7,
1405 norenewalbefore => undef,
1406 auto_renew => 0,
1407 fine => .10,
1408 chargeperiod => 1,
1409 maxissueqty => 20
1413 my $biblio = $builder->build_sample_biblio();
1415 my $item_1 = $builder->build_sample_item(
1417 biblionumber => $biblio->biblionumber,
1418 library => $library2->{branchcode},
1419 itype => $itemtype,
1423 my $item_2= $builder->build_sample_item(
1425 biblionumber => $biblio->biblionumber,
1426 library => $library2->{branchcode},
1427 itype => $itemtype,
1431 my $borrowernumber1 = Koha::Patron->new({
1432 firstname => 'Kyle',
1433 surname => 'Hall',
1434 categorycode => $patron_category->{categorycode},
1435 branchcode => $library2->{branchcode},
1436 })->store->borrowernumber;
1437 my $borrowernumber2 = Koha::Patron->new({
1438 firstname => 'Chelsea',
1439 surname => 'Hall',
1440 categorycode => $patron_category->{categorycode},
1441 branchcode => $library2->{branchcode},
1442 })->store->borrowernumber;
1444 my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1445 my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1447 my $issue = AddIssue( $borrower1, $item_1->barcode );
1449 my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1450 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1452 AddReserve(
1454 branchcode => $library2->{branchcode},
1455 borrowernumber => $borrowernumber2,
1456 biblionumber => $biblio->biblionumber,
1457 priority => 1,
1461 Koha::CirculationRules->set_rules(
1463 categorycode => undef,
1464 itemtype => undef,
1465 branchcode => undef,
1466 rules => {
1467 onshelfholds => 0,
1471 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1472 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1473 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1475 Koha::CirculationRules->set_rules(
1477 categorycode => undef,
1478 itemtype => undef,
1479 branchcode => undef,
1480 rules => {
1481 onshelfholds => 0,
1485 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1486 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1487 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1489 Koha::CirculationRules->set_rules(
1491 categorycode => undef,
1492 itemtype => undef,
1493 branchcode => undef,
1494 rules => {
1495 onshelfholds => 1,
1499 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1500 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1501 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1503 Koha::CirculationRules->set_rules(
1505 categorycode => undef,
1506 itemtype => undef,
1507 branchcode => undef,
1508 rules => {
1509 onshelfholds => 1,
1513 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1514 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1515 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1517 # Setting item not checked out to be not for loan but holdable
1518 $item_2->notforloan(-1)->store;
1520 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1521 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' );
1525 # Don't allow renewing onsite checkout
1526 my $branch = $library->{branchcode};
1528 #Create another record
1529 my $biblio = $builder->build_sample_biblio();
1531 my $item = $builder->build_sample_item(
1533 biblionumber => $biblio->biblionumber,
1534 library => $branch,
1535 itype => $itemtype,
1539 my $borrowernumber = Koha::Patron->new({
1540 firstname => 'fn',
1541 surname => 'dn',
1542 categorycode => $patron_category->{categorycode},
1543 branchcode => $branch,
1544 })->store->borrowernumber;
1546 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1548 my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1549 my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $item->itemnumber );
1550 is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1551 is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1555 my $library = $builder->build({ source => 'Branch' });
1557 my $biblio = $builder->build_sample_biblio();
1559 my $item = $builder->build_sample_item(
1561 biblionumber => $biblio->biblionumber,
1562 library => $library->{branchcode},
1563 itype => $itemtype,
1567 my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1569 my $issue = AddIssue( $patron, $item->barcode );
1570 UpdateFine(
1572 issue_id => $issue->id(),
1573 itemnumber => $item->itemnumber,
1574 borrowernumber => $patron->{borrowernumber},
1575 amount => 1,
1576 type => q{}
1579 UpdateFine(
1581 issue_id => $issue->id(),
1582 itemnumber => $item->itemnumber,
1583 borrowernumber => $patron->{borrowernumber},
1584 amount => 2,
1585 type => q{}
1588 is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1591 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1592 plan tests => 24;
1594 my $homebranch = $builder->build( { source => 'Branch' } );
1595 my $holdingbranch = $builder->build( { source => 'Branch' } );
1596 my $otherbranch = $builder->build( { source => 'Branch' } );
1597 my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1598 my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1600 my $item = $builder->build_sample_item(
1602 homebranch => $homebranch->{branchcode},
1603 holdingbranch => $holdingbranch->{branchcode},
1605 )->unblessed;
1607 set_userenv($holdingbranch);
1609 my $issue = AddIssue( $patron_1->unblessed, $item->{barcode} );
1610 is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
1612 my ( $error, $question, $alerts );
1614 # AllowReturnToBranch == anywhere
1615 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1616 ## Test that unknown barcodes don't generate internal server errors
1617 set_userenv($homebranch);
1618 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1619 ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1620 ## Can be issued from homebranch
1621 set_userenv($homebranch);
1622 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1623 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1624 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1625 ## Can be issued from holdingbranch
1626 set_userenv($holdingbranch);
1627 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1628 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1629 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1630 ## Can be issued from another branch
1631 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1632 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1633 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1635 # AllowReturnToBranch == holdingbranch
1636 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1637 ## Cannot be issued from homebranch
1638 set_userenv($homebranch);
1639 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1640 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1641 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1642 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matched holdingbranch' );
1643 ## Can be issued from holdinbranch
1644 set_userenv($holdingbranch);
1645 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1646 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1647 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1648 ## Cannot be issued from another branch
1649 set_userenv($otherbranch);
1650 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1651 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1652 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1653 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matches holdingbranch' );
1655 # AllowReturnToBranch == homebranch
1656 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1657 ## Can be issued from holdinbranch
1658 set_userenv($homebranch);
1659 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1660 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1661 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1662 ## Cannot be issued from holdinbranch
1663 set_userenv($holdingbranch);
1664 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1665 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1666 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1667 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1668 ## Cannot be issued from holdinbranch
1669 set_userenv($otherbranch);
1670 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1671 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1672 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1673 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1675 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1678 subtest 'AddIssue & AllowReturnToBranch' => sub {
1679 plan tests => 9;
1681 my $homebranch = $builder->build( { source => 'Branch' } );
1682 my $holdingbranch = $builder->build( { source => 'Branch' } );
1683 my $otherbranch = $builder->build( { source => 'Branch' } );
1684 my $patron_1 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1685 my $patron_2 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1687 my $item = $builder->build_sample_item(
1689 homebranch => $homebranch->{branchcode},
1690 holdingbranch => $holdingbranch->{branchcode},
1692 )->unblessed;
1694 set_userenv($holdingbranch);
1696 my $ref_issue = 'Koha::Checkout';
1697 my $issue = AddIssue( $patron_1, $item->{barcode} );
1699 my ( $error, $question, $alerts );
1701 # AllowReturnToBranch == homebranch
1702 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1703 ## Can be issued from homebranch
1704 set_userenv($homebranch);
1705 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from homebranch');
1706 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1707 ## Can be issued from holdinbranch
1708 set_userenv($holdingbranch);
1709 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from holdingbranch');
1710 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1711 ## Can be issued from another branch
1712 set_userenv($otherbranch);
1713 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from otherbranch');
1714 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1716 # AllowReturnToBranch == holdinbranch
1717 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1718 ## Cannot be issued from homebranch
1719 set_userenv($homebranch);
1720 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from homebranch');
1721 ## Can be issued from holdingbranch
1722 set_userenv($holdingbranch);
1723 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - holdingbranch | Can be issued from holdingbranch');
1724 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1725 ## Cannot be issued from another branch
1726 set_userenv($otherbranch);
1727 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from otherbranch');
1729 # AllowReturnToBranch == homebranch
1730 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1731 ## Can be issued from homebranch
1732 set_userenv($homebranch);
1733 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - homebranch | Can be issued from homebranch' );
1734 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1735 ## Cannot be issued from holdinbranch
1736 set_userenv($holdingbranch);
1737 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from holdingbranch' );
1738 ## Cannot be issued from another branch
1739 set_userenv($otherbranch);
1740 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from otherbranch' );
1741 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1744 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1745 plan tests => 8;
1747 my $library = $builder->build( { source => 'Branch' } );
1748 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1749 my $item_1 = $builder->build_sample_item(
1751 library => $library->{branchcode},
1753 )->unblessed;
1754 my $item_2 = $builder->build_sample_item(
1756 library => $library->{branchcode},
1758 )->unblessed;
1760 my ( $error, $question, $alerts );
1762 # Patron cannot issue item_1, they have overdues
1763 my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1764 my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, $yesterday ); # Add an overdue
1766 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1767 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1768 is( keys(%$error) + keys(%$alerts), 0, 'No key for error and alert' . str($error, $question, $alerts) );
1769 is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
1771 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1772 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1773 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1774 is( $error->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
1776 # Patron cannot issue item_1, they are debarred
1777 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1778 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
1779 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1780 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1781 is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
1783 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
1784 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1785 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1786 is( $error->{USERBLOCKEDNOENDDATE}, '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
1789 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
1790 plan tests => 1;
1792 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1793 my $patron_category_x = $builder->build_object(
1795 class => 'Koha::Patron::Categories',
1796 value => { category_type => 'X' }
1799 my $patron = $builder->build_object(
1801 class => 'Koha::Patrons',
1802 value => {
1803 categorycode => $patron_category_x->categorycode,
1804 gonenoaddress => undef,
1805 lost => undef,
1806 debarred => undef,
1807 borrowernotes => ""
1811 my $item_1 = $builder->build_sample_item(
1813 library => $library->{branchcode},
1815 )->unblessed;
1817 my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->{barcode} );
1818 is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
1820 # TODO There are other tests to provide here
1823 subtest 'MultipleReserves' => sub {
1824 plan tests => 3;
1826 my $biblio = $builder->build_sample_biblio();
1828 my $branch = $library2->{branchcode};
1830 my $item_1 = $builder->build_sample_item(
1832 biblionumber => $biblio->biblionumber,
1833 library => $branch,
1834 replacementprice => 12.00,
1835 itype => $itemtype,
1839 my $item_2 = $builder->build_sample_item(
1841 biblionumber => $biblio->biblionumber,
1842 library => $branch,
1843 replacementprice => 12.00,
1844 itype => $itemtype,
1848 my $bibitems = '';
1849 my $priority = '1';
1850 my $resdate = undef;
1851 my $expdate = undef;
1852 my $notes = '';
1853 my $checkitem = undef;
1854 my $found = undef;
1856 my %renewing_borrower_data = (
1857 firstname => 'John',
1858 surname => 'Renewal',
1859 categorycode => $patron_category->{categorycode},
1860 branchcode => $branch,
1862 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
1863 my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
1864 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
1865 my $datedue = dt_from_string( $issue->date_due() );
1866 is (defined $issue->date_due(), 1, "item 1 checked out");
1867 my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
1869 my %reserving_borrower_data1 = (
1870 firstname => 'Katrin',
1871 surname => 'Reservation',
1872 categorycode => $patron_category->{categorycode},
1873 branchcode => $branch,
1875 my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
1876 AddReserve(
1878 branchcode => $branch,
1879 borrowernumber => $reserving_borrowernumber1,
1880 biblionumber => $biblio->biblionumber,
1881 priority => $priority,
1882 reservation_date => $resdate,
1883 expiration_date => $expdate,
1884 notes => $notes,
1885 itemnumber => $checkitem,
1886 found => $found,
1890 my %reserving_borrower_data2 = (
1891 firstname => 'Kirk',
1892 surname => 'Reservation',
1893 categorycode => $patron_category->{categorycode},
1894 branchcode => $branch,
1896 my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
1897 AddReserve(
1899 branchcode => $branch,
1900 borrowernumber => $reserving_borrowernumber2,
1901 biblionumber => $biblio->biblionumber,
1902 priority => $priority,
1903 reservation_date => $resdate,
1904 expiration_date => $expdate,
1905 notes => $notes,
1906 itemnumber => $checkitem,
1907 found => $found,
1912 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1913 is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
1916 my $item_3 = $builder->build_sample_item(
1918 biblionumber => $biblio->biblionumber,
1919 library => $branch,
1920 replacementprice => 12.00,
1921 itype => $itemtype,
1926 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1927 is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
1931 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
1932 plan tests => 5;
1934 my $library = $builder->build( { source => 'Branch' } );
1935 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1937 my $biblionumber = $builder->build_sample_biblio(
1939 branchcode => $library->{branchcode},
1941 )->biblionumber;
1942 my $item_1 = $builder->build_sample_item(
1944 biblionumber => $biblionumber,
1945 library => $library->{branchcode},
1947 )->unblessed;
1949 my $item_2 = $builder->build_sample_item(
1951 biblionumber => $biblionumber,
1952 library => $library->{branchcode},
1954 )->unblessed;
1956 my ( $error, $question, $alerts );
1957 my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, dt_from_string->add( days => 1 ) );
1959 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1960 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1961 cmp_deeply(
1962 { error => $error, alerts => $alerts },
1963 { error => {}, alerts => {} },
1964 'No error or alert should be raised'
1966 is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' );
1968 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1969 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1970 cmp_deeply(
1971 { error => $error, question => $question, alerts => $alerts },
1972 { error => {}, question => {}, alerts => {} },
1973 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1'
1976 # Add a subscription
1977 Koha::Subscription->new({ biblionumber => $biblionumber })->store;
1979 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1980 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1981 cmp_deeply(
1982 { error => $error, question => $question, alerts => $alerts },
1983 { error => {}, question => {}, alerts => {} },
1984 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
1987 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1988 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1989 cmp_deeply(
1990 { error => $error, question => $question, alerts => $alerts },
1991 { error => {}, question => {}, alerts => {} },
1992 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
1996 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
1997 plan tests => 8;
1999 my $library = $builder->build( { source => 'Branch' } );
2000 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2002 # Add 2 items
2003 my $biblionumber = $builder->build_sample_biblio(
2005 branchcode => $library->{branchcode},
2007 )->biblionumber;
2008 my $item_1 = $builder->build_sample_item(
2010 biblionumber => $biblionumber,
2011 library => $library->{branchcode},
2013 )->unblessed;
2014 my $item_2 = $builder->build_sample_item(
2016 biblionumber => $biblionumber,
2017 library => $library->{branchcode},
2019 )->unblessed;
2021 # And the circulation rule
2022 Koha::CirculationRules->search->delete;
2023 Koha::CirculationRules->set_rules(
2025 categorycode => undef,
2026 itemtype => undef,
2027 branchcode => undef,
2028 rules => {
2029 issuelength => 1,
2030 firstremind => 1, # 1 day of grace
2031 finedays => 2, # 2 days of fine per day of overdue
2032 lengthunit => 'days',
2037 # Patron cannot issue item_1, they have overdues
2038 my $now = dt_from_string;
2039 my $five_days_ago = $now->clone->subtract( days => 5 );
2040 my $ten_days_ago = $now->clone->subtract( days => 10 );
2041 AddIssue( $patron, $item_1->{barcode}, $five_days_ago ); # Add an overdue
2042 AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
2043 ; # Add another overdue
2045 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
2046 AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, $now );
2047 my $debarments = Koha::Patron::Debarments::GetDebarments(
2048 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2049 is( scalar(@$debarments), 1 );
2051 # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
2052 # Same for the others
2053 my $expected_expiration = output_pref(
2055 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2056 dateformat => 'sql',
2057 dateonly => 1
2060 is( $debarments->[0]->{expiration}, $expected_expiration );
2062 AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, $now );
2063 $debarments = Koha::Patron::Debarments::GetDebarments(
2064 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2065 is( scalar(@$debarments), 1 );
2066 $expected_expiration = output_pref(
2068 dt => $now->clone->add( days => ( 10 - 1 ) * 2 ),
2069 dateformat => 'sql',
2070 dateonly => 1
2073 is( $debarments->[0]->{expiration}, $expected_expiration );
2075 Koha::Patron::Debarments::DelUniqueDebarment(
2076 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2078 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
2079 AddIssue( $patron, $item_1->{barcode}, $five_days_ago ); # Add an overdue
2080 AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
2081 ; # Add another overdue
2082 AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, $now );
2083 $debarments = Koha::Patron::Debarments::GetDebarments(
2084 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2085 is( scalar(@$debarments), 1 );
2086 $expected_expiration = output_pref(
2088 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2089 dateformat => 'sql',
2090 dateonly => 1
2093 is( $debarments->[0]->{expiration}, $expected_expiration );
2095 AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, $now );
2096 $debarments = Koha::Patron::Debarments::GetDebarments(
2097 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2098 is( scalar(@$debarments), 1 );
2099 $expected_expiration = output_pref(
2101 dt => $now->clone->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
2102 dateformat => 'sql',
2103 dateonly => 1
2106 is( $debarments->[0]->{expiration}, $expected_expiration );
2109 subtest 'AddReturn + suspension_chargeperiod' => sub {
2110 plan tests => 24;
2112 my $library = $builder->build( { source => 'Branch' } );
2113 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2115 my $biblionumber = $builder->build_sample_biblio(
2117 branchcode => $library->{branchcode},
2119 )->biblionumber;
2120 my $item_1 = $builder->build_sample_item(
2122 biblionumber => $biblionumber,
2123 library => $library->{branchcode},
2125 )->unblessed;
2127 # And the issuing rule
2128 Koha::CirculationRules->search->delete;
2129 Koha::CirculationRules->set_rules(
2131 categorycode => '*',
2132 itemtype => '*',
2133 branchcode => '*',
2134 rules => {
2135 issuelength => 1,
2136 firstremind => 0, # 0 day of grace
2137 finedays => 2, # 2 days of fine per day of overdue
2138 suspension_chargeperiod => 1,
2139 lengthunit => 'days',
2144 my $now = dt_from_string;
2145 my $five_days_ago = $now->clone->subtract( days => 5 );
2146 # We want to charge 2 days every day, without grace
2147 # With 5 days of overdue: 5 * Z
2148 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2149 test_debarment_on_checkout(
2151 item => $item_1,
2152 library => $library,
2153 patron => $patron,
2154 due_date => $five_days_ago,
2155 expiration_date => $expected_expiration,
2159 # We want to charge 2 days every 2 days, without grace
2160 # With 5 days of overdue: (5 * 2) / 2
2161 Koha::CirculationRules->set_rule(
2163 categorycode => undef,
2164 branchcode => undef,
2165 itemtype => undef,
2166 rule_name => 'suspension_chargeperiod',
2167 rule_value => '2',
2171 $expected_expiration = $now->clone->add( days => floor( 5 * 2 ) / 2 );
2172 test_debarment_on_checkout(
2174 item => $item_1,
2175 library => $library,
2176 patron => $patron,
2177 due_date => $five_days_ago,
2178 expiration_date => $expected_expiration,
2182 # We want to charge 2 days every 3 days, with 1 day of grace
2183 # With 5 days of overdue: ((5-1) / 3 ) * 2
2184 Koha::CirculationRules->set_rules(
2186 categorycode => undef,
2187 branchcode => undef,
2188 itemtype => undef,
2189 rules => {
2190 suspension_chargeperiod => 3,
2191 firstremind => 1,
2195 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
2196 test_debarment_on_checkout(
2198 item => $item_1,
2199 library => $library,
2200 patron => $patron,
2201 due_date => $five_days_ago,
2202 expiration_date => $expected_expiration,
2206 # Use finesCalendar to know if holiday must be skipped to calculate the due date
2207 # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
2208 Koha::CirculationRules->set_rules(
2210 categorycode => undef,
2211 branchcode => undef,
2212 itemtype => undef,
2213 rules => {
2214 finedays => 2,
2215 suspension_chargeperiod => 1,
2216 firstremind => 0,
2220 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
2221 t::lib::Mocks::mock_preference('SuspensionsCalendar', 'noSuspensionsWhenClosed');
2223 # Adding a holiday 2 days ago
2224 my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
2225 my $two_days_ago = $now->clone->subtract( days => 2 );
2226 $calendar->insert_single_holiday(
2227 day => $two_days_ago->day,
2228 month => $two_days_ago->month,
2229 year => $two_days_ago->year,
2230 title => 'holidayTest-2d',
2231 description => 'holidayDesc 2 days ago'
2233 # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
2234 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
2235 test_debarment_on_checkout(
2237 item => $item_1,
2238 library => $library,
2239 patron => $patron,
2240 due_date => $five_days_ago,
2241 expiration_date => $expected_expiration,
2245 # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
2246 my $two_days_ahead = $now->clone->add( days => 2 );
2247 $calendar->insert_single_holiday(
2248 day => $two_days_ahead->day,
2249 month => $two_days_ahead->month,
2250 year => $two_days_ahead->year,
2251 title => 'holidayTest+2d',
2252 description => 'holidayDesc 2 days ahead'
2255 # Same as above, but we should skip D+2
2256 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
2257 test_debarment_on_checkout(
2259 item => $item_1,
2260 library => $library,
2261 patron => $patron,
2262 due_date => $five_days_ago,
2263 expiration_date => $expected_expiration,
2267 # Adding another holiday, day of expiration date
2268 my $expected_expiration_dt = dt_from_string($expected_expiration);
2269 $calendar->insert_single_holiday(
2270 day => $expected_expiration_dt->day,
2271 month => $expected_expiration_dt->month,
2272 year => $expected_expiration_dt->year,
2273 title => 'holidayTest_exp',
2274 description => 'holidayDesc on expiration date'
2276 # Expiration date will be the day after
2277 test_debarment_on_checkout(
2279 item => $item_1,
2280 library => $library,
2281 patron => $patron,
2282 due_date => $five_days_ago,
2283 expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
2287 test_debarment_on_checkout(
2289 item => $item_1,
2290 library => $library,
2291 patron => $patron,
2292 return_date => $now->clone->add(days => 5),
2293 expiration_date => $now->clone->add(days => 5 + (5 * 2 - 1) ),
2297 test_debarment_on_checkout(
2299 item => $item_1,
2300 library => $library,
2301 patron => $patron,
2302 due_date => $now->clone->add(days => 1),
2303 return_date => $now->clone->add(days => 5),
2304 expiration_date => $now->clone->add(days => 5 + (4 * 2 - 1) ),
2310 subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
2311 plan tests => 2;
2313 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2314 my $patron1 = $builder->build_object(
2316 class => 'Koha::Patrons',
2317 value => {
2318 library => $library->branchcode,
2319 categorycode => $patron_category->{categorycode}
2323 my $patron2 = $builder->build_object(
2325 class => 'Koha::Patrons',
2326 value => {
2327 library => $library->branchcode,
2328 categorycode => $patron_category->{categorycode}
2333 t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
2335 my $item = $builder->build_sample_item(
2337 library => $library->branchcode,
2339 )->unblessed;
2341 my ( $error, $question, $alerts );
2342 my $issue = AddIssue( $patron1->unblessed, $item->{barcode} );
2344 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2345 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->{barcode} );
2346 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' );
2348 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
2349 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->{barcode} );
2350 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' );
2352 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2356 subtest 'AddReturn | is_overdue' => sub {
2357 plan tests => 8;
2359 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'batchmod|moredetail|cronjob|additem|pendingreserves|onpayment');
2360 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
2361 t::lib::Mocks::mock_preference('finesMode', 'production');
2362 t::lib::Mocks::mock_preference('MaxFine', '100');
2364 my $library = $builder->build( { source => 'Branch' } );
2365 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2366 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2367 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2369 my $item = $builder->build_sample_item(
2371 library => $library->{branchcode},
2372 replacementprice => 7
2374 )->unblessed;
2376 Koha::CirculationRules->search->delete;
2377 Koha::CirculationRules->set_rules(
2379 categorycode => undef,
2380 itemtype => undef,
2381 branchcode => undef,
2382 rules => {
2383 issuelength => 6,
2384 lengthunit => 'days',
2385 fine => 1, # Charge 1 every day of overdue
2386 chargeperiod => 1,
2391 my $now = dt_from_string;
2392 my $one_day_ago = $now->clone->subtract( days => 1 );
2393 my $two_days_ago = $now->clone->subtract( days => 2 );
2394 my $five_days_ago = $now->clone->subtract( days => 5 );
2395 my $ten_days_ago = $now->clone->subtract( days => 10 );
2396 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
2398 # No return date specified, today will be used => 10 days overdue charged
2399 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2400 AddReturn( $item->{barcode}, $library->{branchcode} );
2401 is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
2402 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2404 # specify return date 5 days before => no overdue charged
2405 AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
2406 AddReturn( $item->{barcode}, $library->{branchcode}, undef, $ten_days_ago );
2407 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2408 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2410 # specify return date 5 days later => 5 days overdue charged
2411 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2412 AddReturn( $item->{barcode}, $library->{branchcode}, undef, $five_days_ago );
2413 is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
2414 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2416 # specify return date 5 days later, specify exemptfine => no overdue charge
2417 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2418 AddReturn( $item->{barcode}, $library->{branchcode}, 1, $five_days_ago );
2419 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2420 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2422 subtest 'bug 22877' => sub {
2424 plan tests => 3;
2426 my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2428 # Fake fines cronjob on this checkout
2429 my ($fine) =
2430 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2431 $ten_days_ago, $now );
2432 UpdateFine(
2434 issue_id => $issue->issue_id,
2435 itemnumber => $item->{itemnumber},
2436 borrowernumber => $patron->borrowernumber,
2437 amount => $fine,
2438 due => output_pref($ten_days_ago)
2441 is( int( $patron->account->balance() ),
2442 10, "Overdue fine of 10 days overdue" );
2444 # Fake longoverdue with charge and not marking returned
2445 LostItem( $item->{itemnumber}, 'cronjob', 0 );
2446 is( int( $patron->account->balance() ),
2447 17, "Lost fine of 7 plus 10 days overdue" );
2449 # Now we return it today
2450 AddReturn( $item->{barcode}, $library->{branchcode} );
2451 is( int( $patron->account->balance() ),
2452 17, "Should have a single 10 days overdue fine and lost charge" );
2454 # Cleanup
2455 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2458 subtest 'bug 8338 | backdated return resulting in zero amount fine' => sub {
2460 plan tests => 17;
2462 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
2464 my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $one_day_ago ); # date due was 1d ago
2466 # Fake fines cronjob on this checkout
2467 my ($fine) =
2468 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2469 $one_day_ago, $now );
2470 UpdateFine(
2472 issue_id => $issue->issue_id,
2473 itemnumber => $item->{itemnumber},
2474 borrowernumber => $patron->borrowernumber,
2475 amount => $fine,
2476 due => output_pref($one_day_ago)
2479 is( int( $patron->account->balance() ),
2480 1, "Overdue fine of 1 day overdue" );
2482 # Backdated return (dropbox mode example - charge should be removed)
2483 AddReturn( $item->{barcode}, $library->{branchcode}, 1, $one_day_ago );
2484 is( int( $patron->account->balance() ),
2485 0, "Overdue fine should be annulled" );
2486 my $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
2487 is( $lines->count, 0, "Overdue fine accountline has been removed");
2489 $issue = AddIssue( $patron->unblessed, $item->{barcode}, $two_days_ago ); # date due was 2d ago
2491 # Fake fines cronjob on this checkout
2492 ($fine) =
2493 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2494 $two_days_ago, $now );
2495 UpdateFine(
2497 issue_id => $issue->issue_id,
2498 itemnumber => $item->{itemnumber},
2499 borrowernumber => $patron->borrowernumber,
2500 amount => $fine,
2501 due => output_pref($one_day_ago)
2504 is( int( $patron->account->balance() ),
2505 2, "Overdue fine of 2 days overdue" );
2507 # Payment made against fine
2508 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
2509 my $debit = $lines->next;
2510 my $credit = $patron->account->add_credit(
2512 amount => 2,
2513 type => 'PAYMENT',
2514 interface => 'test',
2517 $credit->apply(
2518 { debits => [ $debit ], offset_type => 'Payment' } );
2520 is( int( $patron->account->balance() ),
2521 0, "Overdue fine should be paid off" );
2522 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
2523 is ( $lines->count, 2, "Overdue (debit) and Payment (credit) present");
2524 my $line = $lines->next;
2525 is( $line->amount+0, 2, "Overdue fine amount remains as 2 days");
2526 is( $line->amountoutstanding+0, 0, "Overdue fine amountoutstanding reduced to 0");
2528 # Backdated return (dropbox mode example - charge should be removed)
2529 AddReturn( $item->{barcode}, $library->{branchcode}, undef, $one_day_ago );
2530 is( int( $patron->account->balance() ),
2531 -1, "Refund credit has been applied" );
2532 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber }, { order_by => { '-asc' => 'accountlines_id' }});
2533 is( $lines->count, 3, "Overdue (debit), Payment (credit) and Refund (credit) are all present");
2535 $line = $lines->next;
2536 is($line->amount+0,1, "Overdue fine amount has been reduced to 1");
2537 is($line->amountoutstanding+0,0, "Overdue fine amount outstanding remains at 0");
2538 is($line->status,'RETURNED', "Overdue fine is fixed");
2539 $line = $lines->next;
2540 is($line->amount+0,-2, "Original payment amount remains as 2");
2541 is($line->amountoutstanding+0,0, "Original payment remains applied");
2542 $line = $lines->next;
2543 is($line->amount+0,-1, "Refund amount correctly set to 1");
2544 is($line->amountoutstanding+0,-1, "Refund amount outstanding unspent");
2546 # Cleanup
2547 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2550 subtest 'bug 25417 | backdated return + exemptfine' => sub {
2552 plan tests => 2;
2554 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
2556 my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $one_day_ago ); # date due was 1d ago
2558 # Fake fines cronjob on this checkout
2559 my ($fine) =
2560 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2561 $one_day_ago, $now );
2562 UpdateFine(
2564 issue_id => $issue->issue_id,
2565 itemnumber => $item->{itemnumber},
2566 borrowernumber => $patron->borrowernumber,
2567 amount => $fine,
2568 due => output_pref($one_day_ago)
2571 is( int( $patron->account->balance() ),
2572 1, "Overdue fine of 1 day overdue" );
2574 # Backdated return (dropbox mode example - charge should no longer exist)
2575 AddReturn( $item->{barcode}, $library->{branchcode}, 1, $one_day_ago );
2576 is( int( $patron->account->balance() ),
2577 0, "Overdue fine should be annulled" );
2579 # Cleanup
2580 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2583 subtest 'bug 24075 | backdated return with return datetime matching due datetime' => sub {
2584 plan tests => 7;
2586 t::lib::Mocks::mock_preference( 'CalculateFinesOnBackdate', 1 );
2588 my $due_date = dt_from_string;
2589 my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $due_date );
2591 # Add fine
2592 UpdateFine(
2594 issue_id => $issue->issue_id,
2595 itemnumber => $item->{itemnumber},
2596 borrowernumber => $patron->borrowernumber,
2597 amount => 0.25,
2598 due => output_pref($due_date)
2601 is( $patron->account->balance(),
2602 0.25, 'Overdue fine of $0.25 recorded' );
2604 # Backdate return to exact due date and time
2605 my ( undef, $message ) =
2606 AddReturn( $item->{barcode}, $library->{branchcode},
2607 undef, $due_date );
2609 my $accountline =
2610 Koha::Account::Lines->find( { issue_id => $issue->id } );
2611 ok( !$accountline, 'accountline removed as expected' );
2613 # Re-issue
2614 $issue = AddIssue( $patron->unblessed, $item->{barcode}, $due_date );
2616 # Add fine
2617 UpdateFine(
2619 issue_id => $issue->issue_id,
2620 itemnumber => $item->{itemnumber},
2621 borrowernumber => $patron->borrowernumber,
2622 amount => .25,
2623 due => output_pref($due_date)
2626 is( $patron->account->balance(),
2627 0.25, 'Overdue fine of $0.25 recorded' );
2629 # Partial pay accruing fine
2630 my $lines = Koha::Account::Lines->search(
2632 borrowernumber => $patron->borrowernumber,
2633 issue_id => $issue->id
2636 my $debit = $lines->next;
2637 my $credit = $patron->account->add_credit(
2639 amount => .20,
2640 type => 'PAYMENT',
2641 interface => 'test',
2644 $credit->apply( { debits => [$debit], offset_type => 'Payment' } );
2646 is( $patron->account->balance(), .05, 'Overdue fine reduced to $0.05' );
2648 # Backdate return to exact due date and time
2649 ( undef, $message ) =
2650 AddReturn( $item->{barcode}, $library->{branchcode},
2651 undef, $due_date );
2653 $lines = Koha::Account::Lines->search(
2655 borrowernumber => $patron->borrowernumber,
2656 issue_id => $issue->id
2659 $accountline = $lines->next;
2660 is( $accountline->amountoutstanding + 0,
2661 0, 'Partially paid fee amount outstanding was reduced to 0' );
2662 is( $accountline->amount + 0,
2663 0, 'Partially paid fee amount was reduced to 0' );
2664 is( $patron->account->balance(), -0.20, 'Patron refund recorded' );
2666 # Cleanup
2667 Koha::Account::Lines->search(
2668 { borrowernumber => $patron->borrowernumber } )->delete;
2672 subtest '_FixAccountForLostAndFound' => sub {
2674 plan tests => 5;
2676 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
2677 t::lib::Mocks::mock_preference( 'WhenLostForgiveFine', 0 );
2679 my $processfee_amount = 20;
2680 my $replacement_amount = 99.00;
2681 my $item_type = $builder->build_object(
2682 { class => 'Koha::ItemTypes',
2683 value => {
2684 notforloan => undef,
2685 rentalcharge => 0,
2686 defaultreplacecost => undef,
2687 processfee => $processfee_amount,
2688 rentalcharge_daily => 0,
2692 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2694 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Daria' });
2696 subtest 'Full write-off tests' => sub {
2698 plan tests => 12;
2700 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2701 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2702 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
2704 my $item = $builder->build_sample_item(
2706 biblionumber => $biblio->biblionumber,
2707 library => $library->branchcode,
2708 replacementprice => $replacement_amount,
2709 itype => $item_type->itemtype,
2713 AddIssue( $patron->unblessed, $item->barcode );
2715 # Simulate item marked as lost
2716 $item->itemlost(3)->store;
2717 LostItem( $item->itemnumber, 1 );
2719 my $processing_fee_lines = Koha::Account::Lines->search(
2720 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2721 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2722 my $processing_fee_line = $processing_fee_lines->next;
2723 is( $processing_fee_line->amount + 0,
2724 $processfee_amount, 'The right PROCESSING amount is generated' );
2725 is( $processing_fee_line->amountoutstanding + 0,
2726 $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2728 my $lost_fee_lines = Koha::Account::Lines->search(
2729 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2730 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2731 my $lost_fee_line = $lost_fee_lines->next;
2732 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2733 is( $lost_fee_line->amountoutstanding + 0,
2734 $replacement_amount, 'The right LOST amountoutstanding is generated' );
2735 is( $lost_fee_line->status,
2736 undef, 'The LOST status was not set' );
2738 my $account = $patron->account;
2739 my $debts = $account->outstanding_debits;
2741 # Write off the debt
2742 my $credit = $account->add_credit(
2743 { amount => $account->balance,
2744 type => 'WRITEOFF',
2745 interface => 'test',
2748 $credit->apply( { debits => [ $debts->as_list ], offset_type => 'Writeoff' } );
2750 my $credit_return_id = C4::Circulation::_FixAccountForLostAndFound( $item->itemnumber, $patron->id );
2751 is( $credit_return_id, undef, 'No LOST_FOUND account line added' );
2753 $lost_fee_line->discard_changes; # reload from DB
2754 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2755 is( $lost_fee_line->debit_type_code,
2756 'LOST', 'Lost fee now still has account type of LOST' );
2757 is( $lost_fee_line->status, 'FOUND', "Lost fee now has account status of FOUND");
2759 is( $patron->account->balance, -0, 'The patron balance is 0, everything was written off' );
2762 subtest 'Full payment tests' => sub {
2764 plan tests => 13;
2766 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2768 my $item = $builder->build_sample_item(
2770 biblionumber => $biblio->biblionumber,
2771 library => $library->branchcode,
2772 replacementprice => $replacement_amount,
2773 itype => $item_type->itemtype
2777 AddIssue( $patron->unblessed, $item->barcode );
2779 # Simulate item marked as lost
2780 $item->itemlost(1)->store;
2781 LostItem( $item->itemnumber, 1 );
2783 my $processing_fee_lines = Koha::Account::Lines->search(
2784 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2785 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2786 my $processing_fee_line = $processing_fee_lines->next;
2787 is( $processing_fee_line->amount + 0,
2788 $processfee_amount, 'The right PROCESSING amount is generated' );
2789 is( $processing_fee_line->amountoutstanding + 0,
2790 $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2792 my $lost_fee_lines = Koha::Account::Lines->search(
2793 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2794 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2795 my $lost_fee_line = $lost_fee_lines->next;
2796 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2797 is( $lost_fee_line->amountoutstanding + 0,
2798 $replacement_amount, 'The right LOST amountountstanding is generated' );
2800 my $account = $patron->account;
2801 my $debts = $account->outstanding_debits;
2803 # Write off the debt
2804 my $credit = $account->add_credit(
2805 { amount => $account->balance,
2806 type => 'PAYMENT',
2807 interface => 'test',
2810 $credit->apply( { debits => [ $debts->as_list ], offset_type => 'Payment' } );
2812 my $credit_return_id = C4::Circulation::_FixAccountForLostAndFound( $item->itemnumber, $patron->id );
2813 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2815 is( $credit_return->credit_type_code, 'LOST_FOUND', 'An account line of type LOST_FOUND is added' );
2816 is( $credit_return->amount + 0,
2817 -99.00, 'The account line of type LOST_FOUND has an amount of -99' );
2818 is( $credit_return->amountoutstanding + 0,
2819 -99.00, 'The account line of type LOST_FOUND has an amountoutstanding of -99' );
2821 $lost_fee_line->discard_changes;
2822 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2823 is( $lost_fee_line->debit_type_code,
2824 'LOST', 'Lost fee now still has account type of LOST' );
2825 is( $lost_fee_line->status, 'FOUND', "Lost fee now has account status of FOUND");
2827 is( $patron->account->balance,
2828 -99, 'The patron balance is -99, a credit that equals the lost fee payment' );
2831 subtest 'Test without payment or write off' => sub {
2833 plan tests => 13;
2835 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2837 my $item = $builder->build_sample_item(
2839 biblionumber => $biblio->biblionumber,
2840 library => $library->branchcode,
2841 replacementprice => 23.00,
2842 replacementprice => $replacement_amount,
2843 itype => $item_type->itemtype
2847 AddIssue( $patron->unblessed, $item->barcode );
2849 # Simulate item marked as lost
2850 $item->itemlost(3)->store;
2851 LostItem( $item->itemnumber, 1 );
2853 my $processing_fee_lines = Koha::Account::Lines->search(
2854 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2855 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2856 my $processing_fee_line = $processing_fee_lines->next;
2857 is( $processing_fee_line->amount + 0,
2858 $processfee_amount, 'The right PROCESSING amount is generated' );
2859 is( $processing_fee_line->amountoutstanding + 0,
2860 $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2862 my $lost_fee_lines = Koha::Account::Lines->search(
2863 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2864 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2865 my $lost_fee_line = $lost_fee_lines->next;
2866 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2867 is( $lost_fee_line->amountoutstanding + 0,
2868 $replacement_amount, 'The right LOST amountountstanding is generated' );
2870 my $credit_return_id = C4::Circulation::_FixAccountForLostAndFound( $item->itemnumber, $patron->id );
2871 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2873 is( $credit_return->credit_type_code, 'LOST_FOUND', 'An account line of type LOST_FOUND is added' );
2874 is( $credit_return->amount + 0, -99.00, 'The account line of type LOST_FOUND has an amount of -99' );
2875 is( $credit_return->amountoutstanding + 0, 0, 'The account line of type LOST_FOUND has an amountoutstanding of 0' );
2877 $lost_fee_line->discard_changes;
2878 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2879 is( $lost_fee_line->debit_type_code,
2880 'LOST', 'Lost fee now still has account type of LOST' );
2881 is( $lost_fee_line->status, 'FOUND', "Lost fee now has account status of FOUND");
2883 is( $patron->account->balance, 20, 'The patron balance is 20, still owes the processing fee' );
2886 subtest 'Test with partial payement and write off, and remaining debt' => sub {
2888 plan tests => 16;
2890 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2891 my $item = $builder->build_sample_item(
2893 biblionumber => $biblio->biblionumber,
2894 library => $library->branchcode,
2895 replacementprice => $replacement_amount,
2896 itype => $item_type->itemtype
2900 AddIssue( $patron->unblessed, $item->barcode );
2902 # Simulate item marked as lost
2903 $item->itemlost(1)->store;
2904 LostItem( $item->itemnumber, 1 );
2906 my $processing_fee_lines = Koha::Account::Lines->search(
2907 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2908 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2909 my $processing_fee_line = $processing_fee_lines->next;
2910 is( $processing_fee_line->amount + 0,
2911 $processfee_amount, 'The right PROCESSING amount is generated' );
2912 is( $processing_fee_line->amountoutstanding + 0,
2913 $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2915 my $lost_fee_lines = Koha::Account::Lines->search(
2916 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2917 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2918 my $lost_fee_line = $lost_fee_lines->next;
2919 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2920 is( $lost_fee_line->amountoutstanding + 0,
2921 $replacement_amount, 'The right LOST amountountstanding is generated' );
2923 my $account = $patron->account;
2924 is( $account->balance, $processfee_amount + $replacement_amount, 'Balance is PROCESSING + L' );
2926 # Partially pay fee
2927 my $payment_amount = 27;
2928 my $payment = $account->add_credit(
2929 { amount => $payment_amount,
2930 type => 'PAYMENT',
2931 interface => 'test',
2935 $payment->apply( { debits => [ $lost_fee_line ], offset_type => 'Payment' } );
2937 # Partially write off fee
2938 my $write_off_amount = 25;
2939 my $write_off = $account->add_credit(
2940 { amount => $write_off_amount,
2941 type => 'WRITEOFF',
2942 interface => 'test',
2945 $write_off->apply( { debits => [ $lost_fee_line ], offset_type => 'Writeoff' } );
2947 is( $account->balance,
2948 $processfee_amount + $replacement_amount - $payment_amount - $write_off_amount,
2949 'Payment and write off applied'
2952 # Store the amountoutstanding value
2953 $lost_fee_line->discard_changes;
2954 my $outstanding = $lost_fee_line->amountoutstanding;
2956 my $credit_return_id = C4::Circulation::_FixAccountForLostAndFound( $item->itemnumber, $patron->id );
2957 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2959 is( $account->balance, $processfee_amount - $payment_amount, 'Balance is PROCESSING - PAYMENT (LOST_FOUND)' );
2961 $lost_fee_line->discard_changes;
2962 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2963 is( $lost_fee_line->debit_type_code,
2964 'LOST', 'Lost fee now still has account type of LOST' );
2965 is( $lost_fee_line->status, 'FOUND', "Lost fee now has account status of FOUND");
2967 is( $credit_return->credit_type_code, 'LOST_FOUND', 'An account line of type LOST_FOUND is added' );
2968 is( $credit_return->amount + 0,
2969 ($payment_amount + $outstanding ) * -1,
2970 'The account line of type LOST_FOUND has an amount equal to the payment + outstanding'
2972 is( $credit_return->amountoutstanding + 0,
2973 $payment_amount * -1,
2974 'The account line of type LOST_FOUND has an amountoutstanding equal to the payment'
2977 is( $account->balance,
2978 $processfee_amount - $payment_amount,
2979 'The patron balance is the difference between the PROCESSING and the credit'
2983 subtest 'Partial payement, existing debits and AccountAutoReconcile' => sub {
2985 plan tests => 8;
2987 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2988 my $barcode = 'KD123456793';
2989 my $replacement_amount = 100;
2990 my $processfee_amount = 20;
2992 my $item_type = $builder->build_object(
2993 { class => 'Koha::ItemTypes',
2994 value => {
2995 notforloan => undef,
2996 rentalcharge => 0,
2997 defaultreplacecost => undef,
2998 processfee => 0,
2999 rentalcharge_daily => 0,
3003 my $item = Koha::Item->new(
3005 biblionumber => $biblio->biblionumber,
3006 homebranch => $library->branchcode,
3007 holdingbranch => $library->branchcode,
3008 barcode => $barcode,
3009 replacementprice => $replacement_amount,
3010 itype => $item_type->itemtype
3012 )->store;
3014 AddIssue( $patron->unblessed, $barcode );
3016 # Simulate item marked as lost
3017 $item->itemlost(1)->store;
3018 LostItem( $item->itemnumber, 1 );
3020 my $lost_fee_lines = Koha::Account::Lines->search(
3021 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
3022 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
3023 my $lost_fee_line = $lost_fee_lines->next;
3024 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
3025 is( $lost_fee_line->amountoutstanding + 0,
3026 $replacement_amount, 'The right LOST amountountstanding is generated' );
3028 my $account = $patron->account;
3029 is( $account->balance, $replacement_amount, 'Balance is L' );
3031 # Partially pay fee
3032 my $payment_amount = 27;
3033 my $payment = $account->add_credit(
3034 { amount => $payment_amount,
3035 type => 'PAYMENT',
3036 interface => 'test',
3039 $payment->apply({ debits => [ $lost_fee_line ], offset_type => 'Payment' });
3041 is( $account->balance,
3042 $replacement_amount - $payment_amount,
3043 'Payment applied'
3046 my $manual_debit_amount = 80;
3047 $account->add_debit( { amount => $manual_debit_amount, type => 'OVERDUE', interface =>'test' } );
3049 is( $account->balance, $manual_debit_amount + $replacement_amount - $payment_amount, 'Manual debit applied' );
3051 t::lib::Mocks::mock_preference( 'AccountAutoReconcile', 1 );
3053 my $credit_return_id = C4::Circulation::_FixAccountForLostAndFound( $item->itemnumber, $patron->id );
3054 my $credit_return = Koha::Account::Lines->find($credit_return_id);
3056 is( $account->balance, $manual_debit_amount - $payment_amount, 'Balance is PROCESSING - payment (LOST_FOUND)' );
3058 my $manual_debit = Koha::Account::Lines->search({ borrowernumber => $patron->id, debit_type_code => 'OVERDUE', status => 'UNRETURNED' })->next;
3059 is( $manual_debit->amountoutstanding + 0, $manual_debit_amount - $payment_amount, 'reconcile_balance was called' );
3063 subtest '_FixOverduesOnReturn' => sub {
3064 plan tests => 14;
3066 my $manager = $builder->build_object({ class => "Koha::Patrons" });
3067 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
3069 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
3071 my $branchcode = $library2->{branchcode};
3073 my $item = $builder->build_sample_item(
3075 biblionumber => $biblio->biblionumber,
3076 library => $branchcode,
3077 replacementprice => 99.00,
3078 itype => $itemtype,
3082 my $patron = $builder->build( { source => 'Borrower' } );
3084 ## Start with basic call, should just close out the open fine
3085 my $accountline = Koha::Account::Line->new(
3087 borrowernumber => $patron->{borrowernumber},
3088 debit_type_code => 'OVERDUE',
3089 status => 'UNRETURNED',
3090 itemnumber => $item->itemnumber,
3091 amount => 99.00,
3092 amountoutstanding => 99.00,
3093 interface => 'test',
3095 )->store();
3097 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, undef, 'RETURNED' );
3099 $accountline->_result()->discard_changes();
3101 is( $accountline->amountoutstanding+0, 99, 'Fine has the same amount outstanding as previously' );
3102 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3103 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3105 ## Run again, with exemptfine enabled
3106 $accountline->set(
3108 debit_type_code => 'OVERDUE',
3109 status => 'UNRETURNED',
3110 amountoutstanding => 99.00,
3112 )->store();
3114 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3116 $accountline->_result()->discard_changes();
3117 my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
3119 is( $accountline->amountoutstanding + 0, 0, 'Fine amountoutstanding has been reduced to 0' );
3120 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3121 is( $accountline->status, 'FORGIVEN', 'Open fine ( account type OVERDUE ) has been set to fine forgiven ( status FORGIVEN )');
3122 is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
3123 is( $offset->amount + 0, -99, "Amount of offset is correct" );
3124 my $credit = $offset->credit;
3125 is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
3126 is( $credit->amount + 0, -99, "Credit amount is set correctly" );
3127 is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
3129 # Bug 25417 - Only forgive fines where there is an amount outstanding to forgive
3130 $accountline->set(
3132 debit_type_code => 'OVERDUE',
3133 status => 'UNRETURNED',
3134 amountoutstanding => 0.00,
3136 )->store();
3137 $offset->delete;
3139 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3141 $accountline->_result()->discard_changes();
3142 $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
3143 is( $offset, undef, "No offset created when trying to forgive fine with no outstanding balance" );
3144 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3145 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3148 subtest '_FixAccountForLostAndFound returns undef if patron is deleted' => sub {
3149 plan tests => 1;
3151 my $manager = $builder->build_object({ class => "Koha::Patrons" });
3152 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
3154 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
3156 my $branchcode = $library2->{branchcode};
3158 my $item = $builder->build_sample_item(
3160 biblionumber => $biblio->biblionumber,
3161 library => $branchcode,
3162 replacementprice => 99.00,
3163 itype => $itemtype,
3167 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
3169 ## Start with basic call, should just close out the open fine
3170 my $accountline = Koha::Account::Line->new(
3172 borrowernumber => $patron->id,
3173 debit_type_code => 'LOST',
3174 status => undef,
3175 itemnumber => $item->itemnumber,
3176 amount => 99.00,
3177 amountoutstanding => 99.00,
3178 interface => 'test',
3180 )->store();
3182 $patron->delete();
3184 my $return_value = C4::Circulation::_FixAccountForLostAndFound( $patron->id, $item->itemnumber );
3186 is( $return_value, undef, "_FixAccountForLostAndFound returns undef if patron is deleted" );
3190 subtest 'Set waiting flag' => sub {
3191 plan tests => 11;
3193 my $library_1 = $builder->build( { source => 'Branch' } );
3194 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3195 my $library_2 = $builder->build( { source => 'Branch' } );
3196 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3198 my $item = $builder->build_sample_item(
3200 library => $library_1->{branchcode},
3202 )->unblessed;
3204 set_userenv( $library_2 );
3205 my $reserve_id = AddReserve(
3207 branchcode => $library_2->{branchcode},
3208 borrowernumber => $patron_2->{borrowernumber},
3209 biblionumber => $item->{biblionumber},
3210 priority => 1,
3211 itemnumber => $item->{itemnumber},
3215 set_userenv( $library_1 );
3216 my $do_transfer = 1;
3217 my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
3218 ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
3219 my $hold = Koha::Holds->find( $reserve_id );
3220 is( $hold->found, 'T', 'Hold is in transit' );
3222 my ( $status ) = CheckReserves($item->{itemnumber});
3223 is( $status, 'Reserved', 'Hold is not waiting yet');
3225 set_userenv( $library_2 );
3226 $do_transfer = 0;
3227 AddReturn( $item->{barcode}, $library_2->{branchcode} );
3228 ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
3229 $hold = Koha::Holds->find( $reserve_id );
3230 is( $hold->found, 'W', 'Hold is waiting' );
3231 ( $status ) = CheckReserves($item->{itemnumber});
3232 is( $status, 'Waiting', 'Now the hold is waiting');
3234 #Bug 21944 - Waiting transfer checked in at branch other than pickup location
3235 set_userenv( $library_1 );
3236 (undef, my $messages, undef, undef ) = AddReturn ( $item->{barcode}, $library_1->{branchcode} );
3237 $hold = Koha::Holds->find( $reserve_id );
3238 is( $hold->found, undef, 'Hold is no longer marked waiting' );
3239 is( $hold->priority, 1, "Hold is now priority one again");
3240 is( $hold->waitingdate, undef, "Hold no longer has a waiting date");
3241 is( $hold->itemnumber, $item->{itemnumber}, "Hold has retained its' itemnumber");
3242 is( $messages->{ResFound}->{ResFound}, "Reserved", "Hold is still returned");
3243 is( $messages->{ResFound}->{found}, undef, "Hold is no longer marked found in return message");
3244 is( $messages->{ResFound}->{priority}, 1, "Hold is priority 1 in return message");
3247 subtest 'Cancel transfers on lost items' => sub {
3248 plan tests => 6;
3249 my $library_1 = $builder->build( { source => 'Branch' } );
3250 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3251 my $library_2 = $builder->build( { source => 'Branch' } );
3252 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3253 my $biblio = $builder->build_sample_biblio({branchcode => $library->{branchcode}});
3254 my $item = $builder->build_sample_item({
3255 biblionumber => $biblio->biblionumber,
3256 library => $library_1->{branchcode},
3259 set_userenv( $library_2 );
3260 my $reserve_id = AddReserve(
3262 branchcode => $library_2->{branchcode},
3263 borrowernumber => $patron_2->{borrowernumber},
3264 biblionumber => $item->biblionumber,
3265 priority => 1,
3266 itemnumber => $item->itemnumber,
3270 #Return book and add transfer
3271 set_userenv( $library_1 );
3272 my $do_transfer = 1;
3273 my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
3274 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
3275 C4::Circulation::transferbook({
3276 from_branch => $library_1->{branchcode},
3277 to_branch => $library_2->{branchcode},
3278 barcode => $item->barcode,
3280 my $hold = Koha::Holds->find( $reserve_id );
3281 is( $hold->found, 'T', 'Hold is in transit' );
3283 #Check transfer exists and the items holding branch is the transfer destination branch before marking it as lost
3284 my ($datesent,$frombranch,$tobranch) = GetTransfers($item->itemnumber);
3285 is( $frombranch, $library_1->{branchcode}, 'The transfer is generated from the correct library');
3286 is( $tobranch, $library_2->{branchcode}, 'The transfer is generated to the correct library');
3287 my $itemcheck = Koha::Items->find($item->itemnumber);
3288 is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Items holding branch is the transfers origination branch before it is marked as lost' );
3290 #Simulate item being marked as lost and confirm the transfer is deleted and the items holding branch is the transfers source branch
3291 $item->itemlost(1)->store;
3292 LostItem( $item->itemnumber, 'test', 1 );
3293 ($datesent,$frombranch,$tobranch) = GetTransfers($item->itemnumber);
3294 is( $tobranch, undef, 'The transfer on the lost item has been deleted as the LostItemCancelOutstandingTransfer is enabled');
3295 $itemcheck = Koha::Items->find($item->itemnumber);
3296 is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Lost item with cancelled hold has holding branch equallying the transfers source branch' );
3300 subtest 'CanBookBeIssued | is_overdue' => sub {
3301 plan tests => 3;
3303 # Set a simple circ policy
3304 Koha::CirculationRules->set_rules(
3306 categorycode => undef,
3307 branchcode => undef,
3308 itemtype => undef,
3309 rules => {
3310 maxissueqty => 1,
3311 reservesallowed => 25,
3312 issuelength => 14,
3313 lengthunit => 'days',
3314 renewalsallowed => 1,
3315 renewalperiod => 7,
3316 norenewalbefore => undef,
3317 auto_renew => 0,
3318 fine => .10,
3319 chargeperiod => 1,
3324 my $now = dt_from_string;
3325 my $five_days_go = output_pref({ dt => $now->clone->add( days => 5 ), dateonly => 1});
3326 my $ten_days_go = output_pref({ dt => $now->clone->add( days => 10), dateonly => 1 });
3327 my $library = $builder->build( { source => 'Branch' } );
3328 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
3330 my $item = $builder->build_sample_item(
3332 library => $library->{branchcode},
3334 )->unblessed;
3336 my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $five_days_go ); # date due was 10d ago
3337 my $actualissue = Koha::Checkouts->find( { itemnumber => $item->{itemnumber} } );
3338 is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
3339 my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->{barcode},$ten_days_go, undef, undef, undef);
3340 is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
3341 is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
3344 subtest 'ItemsDeniedRenewal preference' => sub {
3345 plan tests => 18;
3347 C4::Context->set_preference('ItemsDeniedRenewal','');
3349 my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
3350 Koha::CirculationRules->set_rules(
3352 categorycode => '*',
3353 itemtype => '*',
3354 branchcode => $idr_lib->branchcode,
3355 rules => {
3356 reservesallowed => 25,
3357 issuelength => 14,
3358 lengthunit => 'days',
3359 renewalsallowed => 10,
3360 renewalperiod => 7,
3361 norenewalbefore => undef,
3362 auto_renew => 0,
3363 fine => .10,
3364 chargeperiod => 1,
3369 my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
3370 homebranch => $idr_lib->branchcode,
3371 withdrawn => 1,
3372 itype => 'HIDE',
3373 location => 'PROC',
3374 itemcallnumber => undef,
3375 itemnotes => "",
3378 my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
3379 homebranch => $idr_lib->branchcode,
3380 withdrawn => 0,
3381 itype => 'NOHIDE',
3382 location => 'NOPROC'
3386 my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
3387 branchcode => $idr_lib->branchcode,
3390 my $future = dt_from_string->add( days => 1 );
3391 my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3392 returndate => undef,
3393 renewals => 0,
3394 auto_renew => 0,
3395 borrowernumber => $idr_borrower->borrowernumber,
3396 itemnumber => $deny_book->itemnumber,
3397 onsite_checkout => 0,
3398 date_due => $future,
3401 my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3402 returndate => undef,
3403 renewals => 0,
3404 auto_renew => 0,
3405 borrowernumber => $idr_borrower->borrowernumber,
3406 itemnumber => $allow_book->itemnumber,
3407 onsite_checkout => 0,
3408 date_due => $future,
3412 my $idr_rules;
3414 my ( $idr_mayrenew, $idr_error ) =
3415 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3416 is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
3417 is( $idr_error, undef, 'Renewal allowed when no rules' );
3419 $idr_rules="withdrawn: [1]";
3421 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3422 ( $idr_mayrenew, $idr_error ) =
3423 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3424 is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
3425 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
3426 ( $idr_mayrenew, $idr_error ) =
3427 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3428 is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3429 is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3431 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
3433 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3434 ( $idr_mayrenew, $idr_error ) =
3435 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3436 is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
3437 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
3438 ( $idr_mayrenew, $idr_error ) =
3439 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3440 is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3441 is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3443 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
3445 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3446 ( $idr_mayrenew, $idr_error ) =
3447 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3448 is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
3449 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
3450 ( $idr_mayrenew, $idr_error ) =
3451 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3452 is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
3453 is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
3455 $idr_rules="itemcallnumber: [NULL]";
3456 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3457 ( $idr_mayrenew, $idr_error ) =
3458 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3459 is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
3460 $idr_rules="itemcallnumber: ['']";
3461 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3462 ( $idr_mayrenew, $idr_error ) =
3463 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3464 is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
3466 $idr_rules="itemnotes: [NULL]";
3467 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3468 ( $idr_mayrenew, $idr_error ) =
3469 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3470 is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
3471 $idr_rules="itemnotes: ['']";
3472 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3473 ( $idr_mayrenew, $idr_error ) =
3474 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3475 is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
3478 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
3479 plan tests => 2;
3481 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
3482 my $library = $builder->build( { source => 'Branch' } );
3483 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
3485 my $item = $builder->build_sample_item(
3487 library => $library->{branchcode},
3491 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3492 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3493 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3496 subtest 'CanBookBeIssued | notforloan' => sub {
3497 plan tests => 2;
3499 t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
3501 my $library = $builder->build( { source => 'Branch' } );
3502 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
3504 my $itemtype = $builder->build(
3506 source => 'Itemtype',
3507 value => { notforloan => undef, }
3510 my $item = $builder->build_sample_item(
3512 library => $library->{branchcode},
3513 itype => $itemtype->{itemtype},
3516 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
3518 my ( $issuingimpossible, $needsconfirmation );
3521 subtest 'item-level_itypes = 1' => sub {
3522 plan tests => 6;
3524 t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
3525 # Is for loan at item type and item level
3526 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3527 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3528 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3530 # not for loan at item type level
3531 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
3532 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3533 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3534 is_deeply(
3535 $issuingimpossible,
3536 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
3537 'Item can not be issued, not for loan at item type level'
3540 # not for loan at item level
3541 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
3542 $item->notforloan( 1 )->store;
3543 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3544 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3545 is_deeply(
3546 $issuingimpossible,
3547 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
3548 'Item can not be issued, not for loan at item type level'
3552 subtest 'item-level_itypes = 0' => sub {
3553 plan tests => 6;
3555 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
3557 # We set another itemtype for biblioitem
3558 my $itemtype = $builder->build(
3560 source => 'Itemtype',
3561 value => { notforloan => undef, }
3565 # for loan at item type and item level
3566 $item->notforloan(0)->store;
3567 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
3568 ( $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' );
3572 # not for loan at item type level
3573 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
3574 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3575 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3576 is_deeply(
3577 $issuingimpossible,
3578 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
3579 'Item can not be issued, not for loan at item type level'
3582 # not for loan at item level
3583 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
3584 $item->notforloan( 1 )->store;
3585 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3586 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3587 is_deeply(
3588 $issuingimpossible,
3589 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
3590 'Item can not be issued, not for loan at item type level'
3594 # TODO test with AllowNotForLoanOverride = 1
3597 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
3598 plan tests => 1;
3600 t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
3601 my $item = $builder->build_sample_item(
3603 onloan => '2018-01-01',
3607 AddReturn( $item->barcode, $item->homebranch );
3608 $item->discard_changes; # refresh
3609 is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
3613 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
3615 plan tests => 12;
3618 t::lib::Mocks::mock_preference('item-level_itypes', 1);
3620 my $issuing_charges = 15;
3621 my $title = 'A title';
3622 my $author = 'Author, An';
3623 my $barcode = 'WHATARETHEODDS';
3625 my $circ = Test::MockModule->new('C4::Circulation');
3626 $circ->mock(
3627 'GetIssuingCharges',
3628 sub {
3629 return $issuing_charges;
3633 my $library = $builder->build_object({ class => 'Koha::Libraries' });
3634 my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
3635 my $patron = $builder->build_object({
3636 class => 'Koha::Patrons',
3637 value => { branchcode => $library->id }
3640 my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
3641 my $item_id = Koha::Item->new(
3643 biblionumber => $biblio->biblionumber,
3644 homebranch => $library->id,
3645 holdingbranch => $library->id,
3646 barcode => $barcode,
3647 replacementprice => 23.00,
3648 itype => $itemtype->id
3650 )->store->itemnumber;
3651 my $item = Koha::Items->find( $item_id );
3653 my $context = Test::MockModule->new('C4::Context');
3654 $context->mock( userenv => { branch => $library->id } );
3656 # Check the item out
3657 AddIssue( $patron->unblessed, $item->barcode );
3658 t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
3659 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
3660 my %params_renewal = (
3661 timestamp => { -like => $date . "%" },
3662 module => "CIRCULATION",
3663 action => "RENEWAL",
3665 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
3666 AddRenewal( $patron->id, $item->id, $library->id );
3667 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3668 is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
3670 my $checkouts = $patron->checkouts;
3671 # The following will fail if run on 00:00:00
3672 unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
3674 my $lines = Koha::Account::Lines->search({
3675 borrowernumber => $patron->id,
3676 itemnumber => $item->id
3679 is( $lines->count, 2 );
3681 my $line = $lines->next;
3682 is( $line->debit_type_code, 'RENT', 'The issue of item with issuing charge generates an accountline of the correct type' );
3683 is( $line->branchcode, $library->id, 'AddIssuingCharge correctly sets branchcode' );
3684 is( $line->description, '', 'AddIssue does not set a hardcoded description for the accountline' );
3686 $line = $lines->next;
3687 is( $line->debit_type_code, 'RENT_RENEW', 'The renewal of item with issuing charge generates an accountline of the correct type' );
3688 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
3689 is( $line->description, '', 'AddRenewal does not set a hardcoded description for the accountline' );
3691 t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
3693 $context = Test::MockModule->new('C4::Context');
3694 $context->mock( userenv => { branch => undef, interface => 'CRON'} ); #Test statistical logging of renewal via cron (atuo_renew)
3696 my $now = dt_from_string;
3697 $date = output_pref( { dt => $now, dateonly => 1, dateformat => 'iso' } );
3698 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
3699 my $sth = $dbh->prepare("SELECT COUNT(*) FROM statistics WHERE itemnumber = ? AND branch = ?");
3700 $sth->execute($item->id, $library->id);
3701 my ($old_stats_size) = $sth->fetchrow_array;
3702 AddRenewal( $patron->id, $item->id, $library->id );
3703 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3704 $sth->execute($item->id, $library->id);
3705 my ($new_stats_size) = $sth->fetchrow_array;
3706 is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
3707 is( $new_stats_size, $old_stats_size + 1, 'renew statistic successfully added with passed branch' );
3709 AddReturn( $item->id, $library->id, undef, $date );
3710 AddIssue( $patron->unblessed, $item->barcode, $now );
3711 AddRenewal( $patron->id, $item->id, $library->id, undef, undef, 1 );
3712 my $lines_skipped = Koha::Account::Lines->search({
3713 borrowernumber => $patron->id,
3714 itemnumber => $item->id
3716 is( $lines_skipped->count, 5, 'Passing skipfinecalc causes fine calculation on renewal to be skipped' );
3720 subtest 'ProcessOfflinePayment() tests' => sub {
3722 plan tests => 4;
3725 my $amount = 123;
3727 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
3728 my $library = $builder->build_object({ class => 'Koha::Libraries' });
3729 my $result = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
3731 is( $result, 'Success.', 'The right string is returned' );
3733 my $lines = $patron->account->lines;
3734 is( $lines->count, 1, 'line created correctly');
3736 my $line = $lines->next;
3737 is( $line->amount+0, $amount * -1, 'amount picked from params' );
3738 is( $line->branchcode, $library->id, 'branchcode set correctly' );
3742 subtest 'Incremented fee tests' => sub {
3743 plan tests => 19;
3745 my $dt = dt_from_string();
3746 Time::Fake->offset( $dt->epoch );
3748 t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
3750 my $library =
3751 $builder->build_object( { class => 'Koha::Libraries' } )->store;
3753 my $module = new Test::MockModule('C4::Context');
3754 $module->mock( 'userenv', sub { { branch => $library->id } } );
3756 my $patron = $builder->build_object(
3758 class => 'Koha::Patrons',
3759 value => { categorycode => $patron_category->{categorycode} }
3761 )->store;
3763 my $itemtype = $builder->build_object(
3765 class => 'Koha::ItemTypes',
3766 value => {
3767 notforloan => undef,
3768 rentalcharge => 0,
3769 rentalcharge_daily => 1,
3770 rentalcharge_daily_calendar => 0
3773 )->store;
3775 my $item = $builder->build_sample_item(
3777 library => $library->{branchcode},
3778 itype => $itemtype->id,
3782 is( $itemtype->rentalcharge_daily+0,
3783 1, 'Daily rental charge stored and retreived correctly' );
3784 is( $item->effective_itemtype, $itemtype->id,
3785 "Itemtype set correctly for item" );
3787 my $now = dt_from_string;
3788 my $dt_from = $now->clone;
3789 my $dt_to = $now->clone->add( days => 7 );
3790 my $dt_to_renew = $now->clone->add( days => 13 );
3792 # Daily Tests
3793 my $issue =
3794 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3795 my $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3796 is( $accountline->amount+0, 7,
3797 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0"
3799 $accountline->delete();
3800 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3801 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3802 is( $accountline->amount+0, 6,
3803 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0, for renewal"
3805 $accountline->delete();
3806 $issue->delete();
3808 t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
3809 $itemtype->rentalcharge_daily_calendar(1)->store();
3810 $issue =
3811 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3812 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3813 is( $accountline->amount+0, 7,
3814 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1"
3816 $accountline->delete();
3817 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3818 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3819 is( $accountline->amount+0, 6,
3820 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1, for renewal"
3822 $accountline->delete();
3823 $issue->delete();
3825 my $calendar = C4::Calendar->new( branchcode => $library->id );
3826 # DateTime 1..7 (Mon..Sun), C4::Calender 0..6 (Sun..Sat)
3827 my $closed_day =
3828 ( $dt_from->day_of_week == 6 ) ? 0
3829 : ( $dt_from->day_of_week == 7 ) ? 1
3830 : $dt_from->day_of_week + 1;
3831 my $closed_day_name = $dt_from->clone->add(days => 1)->day_name;
3832 $calendar->insert_week_day_holiday(
3833 weekday => $closed_day,
3834 title => 'Test holiday',
3835 description => 'Test holiday'
3837 $issue =
3838 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3839 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3840 is( $accountline->amount+0, 6,
3841 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name"
3843 $accountline->delete();
3844 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3845 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3846 is( $accountline->amount+0, 5,
3847 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name, for renewal"
3849 $accountline->delete();
3850 $issue->delete();
3852 $itemtype->rentalcharge(2)->store;
3853 is( $itemtype->rentalcharge+0, 2,
3854 'Rental charge updated and retreived correctly' );
3855 $issue =
3856 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3857 my $accountlines =
3858 Koha::Account::Lines->search( { itemnumber => $item->id } );
3859 is( $accountlines->count, '2',
3860 "Fixed charge and accrued charge recorded distinctly" );
3861 $accountlines->delete();
3862 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3863 $accountlines = Koha::Account::Lines->search( { itemnumber => $item->id } );
3864 is( $accountlines->count, '2',
3865 "Fixed charge and accrued charge recorded distinctly, for renewal" );
3866 $accountlines->delete();
3867 $issue->delete();
3868 $itemtype->rentalcharge(0)->store;
3869 is( $itemtype->rentalcharge+0, 0,
3870 'Rental charge reset and retreived correctly' );
3872 # Hourly
3873 Koha::CirculationRules->set_rule(
3875 categorycode => $patron->categorycode,
3876 itemtype => $itemtype->id,
3877 branchcode => $library->id,
3878 rule_name => 'lengthunit',
3879 rule_value => 'hours',
3883 $itemtype->rentalcharge_hourly('0.25')->store();
3884 is( $itemtype->rentalcharge_hourly,
3885 '0.25', 'Hourly rental charge stored and retreived correctly' );
3887 $dt_to = $now->clone->add( hours => 168 );
3888 $dt_to_renew = $now->clone->add( hours => 312 );
3890 $itemtype->rentalcharge_hourly_calendar(0)->store();
3891 $issue =
3892 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3893 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3894 is( $accountline->amount + 0, 42,
3895 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0 (168h * 0.25u)" );
3896 $accountline->delete();
3897 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3898 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3899 is( $accountline->amount + 0, 36,
3900 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0, for renewal (312h - 168h * 0.25u)" );
3901 $accountline->delete();
3902 $issue->delete();
3904 $itemtype->rentalcharge_hourly_calendar(1)->store();
3905 $issue =
3906 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3907 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3908 is( $accountline->amount + 0, 36,
3909 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name (168h - 24h * 0.25u)" );
3910 $accountline->delete();
3911 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3912 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3913 is( $accountline->amount + 0, 30,
3914 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name, for renewal (312h - 168h - 24h * 0.25u" );
3915 $accountline->delete();
3916 $issue->delete();
3918 $calendar->delete_holiday( weekday => $closed_day );
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, 42,
3923 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 (168h - 0h * 0.25u" );
3924 $accountline->delete();
3925 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3926 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3927 is( $accountline->amount + 0, 36,
3928 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1, for renewal (312h - 168h - 0h * 0.25u)" );
3929 $accountline->delete();
3930 $issue->delete();
3931 Time::Fake->reset;
3934 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
3935 plan tests => 2;
3937 t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
3938 t::lib::Mocks::mock_preference('item-level_itypes', 1);
3940 my $library =
3941 $builder->build_object( { class => 'Koha::Libraries' } )->store;
3942 my $patron = $builder->build_object(
3944 class => 'Koha::Patrons',
3945 value => { categorycode => $patron_category->{categorycode} }
3947 )->store;
3949 my $itemtype = $builder->build_object(
3951 class => 'Koha::ItemTypes',
3952 value => {
3953 notforloan => 0,
3954 rentalcharge => 0,
3955 rentalcharge_daily => 0
3960 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
3961 my $item = $builder->build_object(
3963 class => 'Koha::Items',
3964 value => {
3965 homebranch => $library->id,
3966 holdingbranch => $library->id,
3967 notforloan => 0,
3968 itemlost => 0,
3969 withdrawn => 0,
3970 itype => $itemtype->id,
3971 biblionumber => $biblioitem->{biblionumber},
3972 biblioitemnumber => $biblioitem->{biblioitemnumber},
3975 )->store;
3977 my ( $issuingimpossible, $needsconfirmation );
3978 my $dt_from = dt_from_string();
3979 my $dt_due = $dt_from->clone->add( days => 3 );
3981 $itemtype->rentalcharge(1)->store;
3982 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3983 is_deeply( $needsconfirmation, { RENTALCHARGE => '1.00' }, 'Item needs rentalcharge confirmation to be issued' );
3984 $itemtype->rentalcharge('0')->store;
3985 $itemtype->rentalcharge_daily(1)->store;
3986 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3987 is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
3988 $itemtype->rentalcharge_daily('0')->store;
3991 subtest 'Do not return on renewal (LOST charge)' => sub {
3992 plan tests => 1;
3994 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'onpayment');
3995 my $library = $builder->build_object( { class => "Koha::Libraries" } );
3996 my $manager = $builder->build_object( { class => "Koha::Patrons" } );
3997 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
3999 my $biblio = $builder->build_sample_biblio;
4001 my $item = $builder->build_sample_item(
4003 biblionumber => $biblio->biblionumber,
4004 library => $library->branchcode,
4005 replacementprice => 99.00,
4006 itype => $itemtype,
4010 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
4011 AddIssue( $patron->unblessed, $item->barcode );
4013 my $accountline = Koha::Account::Line->new(
4015 borrowernumber => $patron->borrowernumber,
4016 debit_type_code => 'LOST',
4017 status => undef,
4018 itemnumber => $item->itemnumber,
4019 amount => 12,
4020 amountoutstanding => 12,
4021 interface => 'something',
4023 )->store();
4025 # AddRenewal doesn't call _FixAccountForLostAndFound
4026 AddIssue( $patron->unblessed, $item->barcode );
4028 is( $patron->checkouts->count, 1,
4029 'Renewal should not return the item even if a LOST payment has been made earlier'
4033 subtest 'Filling a hold should cancel existing transfer' => sub {
4034 plan tests => 4;
4036 t::lib::Mocks::mock_preference('AutomaticItemReturn', 1);
4038 my $libraryA = $builder->build_object( { class => 'Koha::Libraries' } );
4039 my $libraryB = $builder->build_object( { class => 'Koha::Libraries' } );
4040 my $patron = $builder->build_object(
4042 class => 'Koha::Patrons',
4043 value => {
4044 categorycode => $patron_category->{categorycode},
4045 branchcode => $libraryA->branchcode,
4048 )->store;
4050 my $item = $builder->build_sample_item({
4051 homebranch => $libraryB->branchcode,
4054 my ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
4055 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 1, "We generate a transfer on checkin");
4056 AddReserve({
4057 branchcode => $libraryA->branchcode,
4058 borrowernumber => $patron->borrowernumber,
4059 biblionumber => $item->biblionumber,
4060 itemnumber => $item->itemnumber
4062 my $reserves = Koha::Holds->search({ itemnumber => $item->itemnumber });
4063 is( $reserves->count, 1, "Reserve is placed");
4064 ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
4065 my $reserve = $reserves->next;
4066 ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 0, $reserve->reserve_id );
4067 $reserve->discard_changes;
4068 ok( $reserve->found eq 'W', "Reserve is marked waiting" );
4069 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 0, "No outstanding transfers when hold is waiting");
4072 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddReturn' => sub {
4074 plan tests => 4;
4076 t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
4077 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
4078 my $patron = $builder->build_object(
4080 class => 'Koha::Patrons',
4081 value => { categorycode => $patron_category->{categorycode} }
4085 my $biblionumber = $builder->build_sample_biblio(
4087 branchcode => $library->branchcode,
4089 )->biblionumber;
4091 # And the circulation rule
4092 Koha::CirculationRules->search->delete;
4093 Koha::CirculationRules->set_rules(
4095 categorycode => undef,
4096 itemtype => undef,
4097 branchcode => undef,
4098 rules => {
4099 issuelength => 14,
4100 lengthunit => 'days',
4104 $builder->build(
4106 source => 'CirculationRule',
4107 value => {
4108 branchcode => undef,
4109 categorycode => undef,
4110 itemtype => undef,
4111 rule_name => 'refund',
4112 rule_value => 1
4117 subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
4118 plan tests => 3;
4120 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4121 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
4123 my $lost_on = dt_from_string->subtract( days => 7 )->date;
4125 my $item = $builder->build_sample_item(
4127 biblionumber => $biblionumber,
4128 library => $library->branchcode,
4129 replacementprice => '42',
4132 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4133 LostItem( $item->itemnumber, 'cli', 0 );
4134 $item->_result->itemlost(1);
4135 $item->_result->itemlost_on( $lost_on );
4136 $item->_result->update();
4138 my $a = Koha::Account::Lines->search(
4140 itemnumber => $item->id,
4141 borrowernumber => $patron->borrowernumber
4143 )->next;
4144 ok( $a, "Found accountline for lost fee" );
4145 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4146 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4147 $a = $a->get_from_storage;
4148 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4149 $a->delete;
4152 subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
4153 plan tests => 3;
4155 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4156 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4158 my $lost_on = dt_from_string->subtract( days => 6 )->date;
4160 my $item = $builder->build_sample_item(
4162 biblionumber => $biblionumber,
4163 library => $library->branchcode,
4164 replacementprice => '42',
4167 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4168 LostItem( $item->itemnumber, 'cli', 0 );
4169 $item->_result->itemlost(1);
4170 $item->_result->itemlost_on( $lost_on );
4171 $item->_result->update();
4173 my $a = Koha::Account::Lines->search(
4175 itemnumber => $item->id,
4176 borrowernumber => $patron->borrowernumber
4178 )->next;
4179 ok( $a, "Found accountline for lost fee" );
4180 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4181 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4182 $a = $a->get_from_storage;
4183 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4184 $a->delete;
4187 subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
4188 plan tests => 3;
4190 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4191 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4193 my $lost_on = dt_from_string->subtract( days => 7 )->date;
4195 my $item = $builder->build_sample_item(
4197 biblionumber => $biblionumber,
4198 library => $library->branchcode,
4199 replacementprice => '42',
4202 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4203 LostItem( $item->itemnumber, 'cli', 0 );
4204 $item->_result->itemlost(1);
4205 $item->_result->itemlost_on( $lost_on );
4206 $item->_result->update();
4208 my $a = Koha::Account::Lines->search(
4210 itemnumber => $item->id,
4211 borrowernumber => $patron->borrowernumber
4213 )->next;
4214 ok( $a, "Found accountline for lost fee" );
4215 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4216 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4217 $a = $a->get_from_storage;
4218 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4219 $a->delete;
4222 subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
4223 plan tests => 3;
4225 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4226 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4228 my $lost_on = dt_from_string->subtract( days => 8 )->date;
4230 my $item = $builder->build_sample_item(
4232 biblionumber => $biblionumber,
4233 library => $library->branchcode,
4234 replacementprice => '42',
4237 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4238 LostItem( $item->itemnumber, 'cli', 0 );
4239 $item->_result->itemlost(1);
4240 $item->_result->itemlost_on( $lost_on );
4241 $item->_result->update();
4243 my $a = Koha::Account::Lines->search(
4245 itemnumber => $item->id,
4246 borrowernumber => $patron->borrowernumber
4249 $a = $a->next;
4250 ok( $a, "Found accountline for lost fee" );
4251 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4252 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4253 $a = $a->get_from_storage;
4254 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4255 $a->delete;
4259 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub {
4261 plan tests => 4;
4263 t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
4264 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
4265 my $patron = $builder->build_object(
4267 class => 'Koha::Patrons',
4268 value => { categorycode => $patron_category->{categorycode} }
4271 my $patron2 = $builder->build_object(
4273 class => 'Koha::Patrons',
4274 value => { categorycode => $patron_category->{categorycode} }
4278 my $biblionumber = $builder->build_sample_biblio(
4280 branchcode => $library->branchcode,
4282 )->biblionumber;
4284 # And the circulation rule
4285 Koha::CirculationRules->search->delete;
4286 Koha::CirculationRules->set_rules(
4288 categorycode => undef,
4289 itemtype => undef,
4290 branchcode => undef,
4291 rules => {
4292 issuelength => 14,
4293 lengthunit => 'days',
4297 $builder->build(
4299 source => 'CirculationRule',
4300 value => {
4301 branchcode => undef,
4302 categorycode => undef,
4303 itemtype => undef,
4304 rule_name => 'refund',
4305 rule_value => 1
4310 subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
4311 plan tests => 3;
4313 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4314 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
4316 my $lost_on = dt_from_string->subtract( days => 7 )->date;
4318 my $item = $builder->build_sample_item(
4320 biblionumber => $biblionumber,
4321 library => $library->branchcode,
4322 replacementprice => '42',
4325 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4326 LostItem( $item->itemnumber, 'cli', 0 );
4327 $item->_result->itemlost(1);
4328 $item->_result->itemlost_on( $lost_on );
4329 $item->_result->update();
4331 my $a = Koha::Account::Lines->search(
4333 itemnumber => $item->id,
4334 borrowernumber => $patron->borrowernumber
4336 )->next;
4337 ok( $a, "Found accountline for lost fee" );
4338 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4339 $issue = AddIssue( $patron2->unblessed, $item->barcode );
4340 $a = $a->get_from_storage;
4341 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4342 $a->delete;
4343 $issue->delete;
4346 subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
4347 plan tests => 3;
4349 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4350 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4352 my $lost_on = dt_from_string->subtract( days => 6 )->date;
4354 my $item = $builder->build_sample_item(
4356 biblionumber => $biblionumber,
4357 library => $library->branchcode,
4358 replacementprice => '42',
4361 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4362 LostItem( $item->itemnumber, 'cli', 0 );
4363 $item->_result->itemlost(1);
4364 $item->_result->itemlost_on( $lost_on );
4365 $item->_result->update();
4367 my $a = Koha::Account::Lines->search(
4369 itemnumber => $item->id,
4370 borrowernumber => $patron->borrowernumber
4372 )->next;
4373 ok( $a, "Found accountline for lost fee" );
4374 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4375 $issue = AddIssue( $patron2->unblessed, $item->barcode );
4376 $a = $a->get_from_storage;
4377 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4378 $a->delete;
4381 subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
4382 plan tests => 3;
4384 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4385 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4387 my $lost_on = dt_from_string->subtract( days => 7 )->date;
4389 my $item = $builder->build_sample_item(
4391 biblionumber => $biblionumber,
4392 library => $library->branchcode,
4393 replacementprice => '42',
4396 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4397 LostItem( $item->itemnumber, 'cli', 0 );
4398 $item->_result->itemlost(1);
4399 $item->_result->itemlost_on( $lost_on );
4400 $item->_result->update();
4402 my $a = Koha::Account::Lines->search(
4404 itemnumber => $item->id,
4405 borrowernumber => $patron->borrowernumber
4407 )->next;
4408 ok( $a, "Found accountline for lost fee" );
4409 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4410 $issue = AddIssue( $patron2->unblessed, $item->barcode );
4411 $a = $a->get_from_storage;
4412 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4413 $a->delete;
4416 subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
4417 plan tests => 3;
4419 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4420 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4422 my $lost_on = dt_from_string->subtract( days => 8 )->date;
4424 my $item = $builder->build_sample_item(
4426 biblionumber => $biblionumber,
4427 library => $library->branchcode,
4428 replacementprice => '42',
4431 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4432 LostItem( $item->itemnumber, 'cli', 0 );
4433 $item->_result->itemlost(1);
4434 $item->_result->itemlost_on( $lost_on );
4435 $item->_result->update();
4437 my $a = Koha::Account::Lines->search(
4439 itemnumber => $item->id,
4440 borrowernumber => $patron->borrowernumber
4443 $a = $a->next;
4444 ok( $a, "Found accountline for lost fee" );
4445 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4446 $issue = AddIssue( $patron2->unblessed, $item->barcode );
4447 $a = $a->get_from_storage;
4448 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4449 $a->delete;
4453 subtest 'transferbook tests' => sub {
4454 plan tests => 9;
4456 throws_ok
4457 { C4::Circulation::transferbook({}); }
4458 'Koha::Exceptions::MissingParameter',
4459 'Koha::Patron->store raises an exception on missing params';
4461 throws_ok
4462 { C4::Circulation::transferbook({to_branch=>'anything'}); }
4463 'Koha::Exceptions::MissingParameter',
4464 'Koha::Patron->store raises an exception on missing params';
4466 throws_ok
4467 { C4::Circulation::transferbook({from_branch=>'anything'}); }
4468 'Koha::Exceptions::MissingParameter',
4469 'Koha::Patron->store raises an exception on missing params';
4471 my ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here'});
4472 is( $doreturn, 0, "No return without barcode");
4473 ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
4474 is( $messages->{BadBarcode}, undef, "No barcode passed means undef BadBarcode" );
4476 ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here',barcode=>'BadBarcode'});
4477 is( $doreturn, 0, "No return without barcode");
4478 ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
4479 is( $messages->{BadBarcode}, 'BadBarcode', "No barcode passed means undef BadBarcode" );
4483 $schema->storage->txn_rollback;
4484 C4::Context->clear_syspref_cache();
4485 $branches = Koha::Libraries->search();
4486 for my $branch ( $branches->next ) {
4487 my $key = $branch->branchcode . "_holidays";
4488 $cache->clear_from_cache($key);