Bug 21049: Fix value of material select for Rancor 007 widget
[koha.git] / t / db_dependent / Circulation.t
blobfa4e6342ac9b590160b2dbe03429159f24437dbf
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 => 126;
22 use Test::MockModule;
24 use Data::Dumper;
25 use DateTime;
26 use POSIX qw( floor );
27 use t::lib::Mocks;
28 use t::lib::TestBuilder;
30 use C4::Accounts;
31 use C4::Calendar;
32 use C4::Circulation;
33 use C4::Biblio;
34 use C4::Items;
35 use C4::Log;
36 use C4::Reserves;
37 use C4::Overdues qw(UpdateFine CalcFine);
38 use Koha::DateUtils;
39 use Koha::Database;
40 use Koha::IssuingRules;
41 use Koha::Items;
42 use Koha::Checkouts;
43 use Koha::Patrons;
44 use Koha::CirculationRules;
45 use Koha::Subscriptions;
46 use Koha::Account::Lines;
47 use Koha::Account::Offsets;
48 use Koha::ActionLogs;
50 my $schema = Koha::Database->schema;
51 $schema->storage->txn_begin;
52 my $builder = t::lib::TestBuilder->new;
53 my $dbh = C4::Context->dbh;
55 # Start transaction
56 $dbh->{RaiseError} = 1;
58 my $cache = Koha::Caches->get_instance();
59 $dbh->do(q|DELETE FROM special_holidays|);
60 $dbh->do(q|DELETE FROM repeatable_holidays|);
61 $cache->clear_from_cache('single_holidays');
63 # Start with a clean slate
64 $dbh->do('DELETE FROM issues');
65 $dbh->do('DELETE FROM borrowers');
67 my $library = $builder->build({
68 source => 'Branch',
69 });
70 my $library2 = $builder->build({
71 source => 'Branch',
72 });
73 my $itemtype = $builder->build(
75 source => 'Itemtype',
76 value => {
77 notforloan => undef,
78 rentalcharge => 0,
79 rentalcharge_daily => 0,
80 defaultreplacecost => undef,
81 processfee => undef
84 )->{itemtype};
85 my $patron_category = $builder->build(
87 source => 'Category',
88 value => {
89 category_type => 'P',
90 enrolmentfee => 0,
91 BlockExpiredPatronOpacActions => -1, # Pick the pref value
96 my $CircControl = C4::Context->preference('CircControl');
97 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
99 my $item = {
100 homebranch => $library2->{branchcode},
101 holdingbranch => $library2->{branchcode}
104 my $borrower = {
105 branchcode => $library2->{branchcode}
108 # No userenv, PickupLibrary
109 t::lib::Mocks::mock_preference('IndependentBranches', '0');
110 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
112 C4::Context->preference('CircControl'),
113 'PickupLibrary',
114 'CircControl changed to PickupLibrary'
117 C4::Circulation::_GetCircControlBranch($item, $borrower),
118 $item->{$HomeOrHoldingBranch},
119 '_GetCircControlBranch returned item branch (no userenv defined)'
122 # No userenv, PatronLibrary
123 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
125 C4::Context->preference('CircControl'),
126 'PatronLibrary',
127 'CircControl changed to PatronLibrary'
130 C4::Circulation::_GetCircControlBranch($item, $borrower),
131 $borrower->{branchcode},
132 '_GetCircControlBranch returned borrower branch'
135 # No userenv, ItemHomeLibrary
136 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
138 C4::Context->preference('CircControl'),
139 'ItemHomeLibrary',
140 'CircControl changed to ItemHomeLibrary'
143 $item->{$HomeOrHoldingBranch},
144 C4::Circulation::_GetCircControlBranch($item, $borrower),
145 '_GetCircControlBranch returned item branch'
148 # Now, set a userenv
149 t::lib::Mocks::mock_userenv({ branchcode => $library2->{branchcode} });
150 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
152 # Userenv set, PickupLibrary
153 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
155 C4::Context->preference('CircControl'),
156 'PickupLibrary',
157 'CircControl changed to PickupLibrary'
160 C4::Circulation::_GetCircControlBranch($item, $borrower),
161 $library2->{branchcode},
162 '_GetCircControlBranch returned current branch'
165 # Userenv set, PatronLibrary
166 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
168 C4::Context->preference('CircControl'),
169 'PatronLibrary',
170 'CircControl changed to PatronLibrary'
173 C4::Circulation::_GetCircControlBranch($item, $borrower),
174 $borrower->{branchcode},
175 '_GetCircControlBranch returned borrower branch'
178 # Userenv set, ItemHomeLibrary
179 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
181 C4::Context->preference('CircControl'),
182 'ItemHomeLibrary',
183 'CircControl changed to ItemHomeLibrary'
186 C4::Circulation::_GetCircControlBranch($item, $borrower),
187 $item->{$HomeOrHoldingBranch},
188 '_GetCircControlBranch returned item branch'
191 # Reset initial configuration
192 t::lib::Mocks::mock_preference('CircControl', $CircControl);
194 C4::Context->preference('CircControl'),
195 $CircControl,
196 'CircControl reset to its initial value'
199 # Set a simple circ policy
200 $dbh->do('DELETE FROM issuingrules');
201 Koha::CirculationRules->search()->delete();
202 $dbh->do(
203 q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
204 issuelength, lengthunit,
205 renewalsallowed, renewalperiod,
206 norenewalbefore, auto_renew,
207 fine, chargeperiod)
208 VALUES (?, ?, ?, ?,
209 ?, ?,
210 ?, ?,
211 ?, ?,
212 ?, ?
216 '*', '*', '*', 25,
217 14, 'days',
218 1, 7,
219 undef, 0,
220 .10, 1
223 my ( $reused_itemnumber_1, $reused_itemnumber_2 );
225 # CanBookBeRenewed tests
226 C4::Context->set_preference('ItemsDeniedRenewal','');
227 # Generate test biblio
228 my $biblio = $builder->build_sample_biblio();
230 my $branch = $library2->{branchcode};
232 my $item_1 = $builder->build_sample_item(
234 biblionumber => $biblio->biblionumber,
235 library => $branch,
236 replacementprice => 12.00,
237 itype => $itemtype
240 $reused_itemnumber_1 = $item_1->itemnumber;
242 my $item_2 = $builder->build_sample_item(
244 biblionumber => $biblio->biblionumber,
245 library => $branch,
246 replacementprice => 23.00,
247 itype => $itemtype
250 $reused_itemnumber_2 = $item_2->itemnumber;
252 my $item_3 = $builder->build_sample_item(
254 biblionumber => $biblio->biblionumber,
255 library => $branch,
256 replacementprice => 23.00,
257 itype => $itemtype
261 # Create borrowers
262 my %renewing_borrower_data = (
263 firstname => 'John',
264 surname => 'Renewal',
265 categorycode => $patron_category->{categorycode},
266 branchcode => $branch,
269 my %reserving_borrower_data = (
270 firstname => 'Katrin',
271 surname => 'Reservation',
272 categorycode => $patron_category->{categorycode},
273 branchcode => $branch,
276 my %hold_waiting_borrower_data = (
277 firstname => 'Kyle',
278 surname => 'Reservation',
279 categorycode => $patron_category->{categorycode},
280 branchcode => $branch,
283 my %restricted_borrower_data = (
284 firstname => 'Alice',
285 surname => 'Reservation',
286 categorycode => $patron_category->{categorycode},
287 debarred => '3228-01-01',
288 branchcode => $branch,
291 my %expired_borrower_data = (
292 firstname => 'Ça',
293 surname => 'Glisse',
294 categorycode => $patron_category->{categorycode},
295 branchcode => $branch,
296 dateexpiry => dt_from_string->subtract( months => 1 ),
299 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
300 my $reserving_borrowernumber = Koha::Patron->new(\%reserving_borrower_data)->store->borrowernumber;
301 my $hold_waiting_borrowernumber = Koha::Patron->new(\%hold_waiting_borrower_data)->store->borrowernumber;
302 my $restricted_borrowernumber = Koha::Patron->new(\%restricted_borrower_data)->store->borrowernumber;
303 my $expired_borrowernumber = Koha::Patron->new(\%expired_borrower_data)->store->borrowernumber;
305 my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
306 my $restricted_borrower = Koha::Patrons->find( $restricted_borrowernumber )->unblessed;
307 my $expired_borrower = Koha::Patrons->find( $expired_borrowernumber )->unblessed;
309 my $bibitems = '';
310 my $priority = '1';
311 my $resdate = undef;
312 my $expdate = undef;
313 my $notes = '';
314 my $checkitem = undef;
315 my $found = undef;
317 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
318 my $datedue = dt_from_string( $issue->date_due() );
319 is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
321 my $issue2 = AddIssue( $renewing_borrower, $item_2->barcode);
322 $datedue = dt_from_string( $issue->date_due() );
323 is (defined $issue2, 1, "Item 2 checked out, due date: " . $issue2->date_due());
326 my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $item_1->itemnumber } )->borrowernumber;
327 is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
329 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
330 is( $renewokay, 1, 'Can renew, no holds for this title or item');
333 # Biblio-level hold, renewal test
334 AddReserve(
335 $branch, $reserving_borrowernumber, $biblio->biblionumber,
336 $bibitems, $priority, $resdate, $expdate, $notes,
337 'a title', $checkitem, $found
340 # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
341 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
342 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
343 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
344 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
345 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
346 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
348 # Now let's add an item level hold, we should no longer be able to renew the item
349 my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
351 borrowernumber => $hold_waiting_borrowernumber,
352 biblionumber => $biblio->biblionumber,
353 itemnumber => $item_1->itemnumber,
354 branchcode => $branch,
355 priority => 3,
358 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
359 is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
360 $hold->delete();
362 # 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
363 # be able to renew these items
364 $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
366 borrowernumber => $hold_waiting_borrowernumber,
367 biblionumber => $biblio->biblionumber,
368 itemnumber => $item_3->itemnumber,
369 branchcode => $branch,
370 priority => 0,
371 found => 'W'
374 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
375 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
376 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
377 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
378 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
380 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
381 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
382 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
384 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
385 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
386 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
388 my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
389 my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber )->unblessed;
390 AddIssue($reserving_borrower, $item_3->barcode);
391 my $reserve = $dbh->selectrow_hashref(
392 'SELECT * FROM old_reserves WHERE reserve_id = ?',
393 { Slice => {} },
394 $reserveid
396 is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
398 # Item-level hold, renewal test
399 AddReserve(
400 $branch, $reserving_borrowernumber, $biblio->biblionumber,
401 $bibitems, $priority, $resdate, $expdate, $notes,
402 'a title', $item_1->itemnumber, $found
405 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
406 is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
407 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
409 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber, 1);
410 is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
412 # Items can't fill hold for reasons
413 ModItem({ notforloan => 1 }, $biblio->biblionumber, $item_1->itemnumber);
414 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
415 is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
416 ModItem({ notforloan => 0, itype => $itemtype }, $biblio->biblionumber, $item_1->itemnumber);
418 # FIXME: Add more for itemtype not for loan etc.
420 # Restricted users cannot renew when RestrictionBlockRenewing is enabled
421 my $item_5 = $builder->build_sample_item(
423 biblionumber => $biblio->biblionumber,
424 library => $branch,
425 replacementprice => 23.00,
426 itype => $itemtype,
429 my $datedue5 = AddIssue($restricted_borrower, $item_5->barcode);
430 is (defined $datedue5, 1, "Item with date due checked out, due date: $datedue5");
432 t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
433 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
434 is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
435 ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrowernumber, $item_5->itemnumber);
436 is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
438 # Users cannot renew an overdue item
439 my $item_6 = $builder->build_sample_item(
441 biblionumber => $biblio->biblionumber,
442 library => $branch,
443 replacementprice => 23.00,
444 itype => $itemtype,
448 my $item_7 = $builder->build_sample_item(
450 biblionumber => $biblio->biblionumber,
451 library => $branch,
452 replacementprice => 23.00,
453 itype => $itemtype,
457 my $datedue6 = AddIssue( $renewing_borrower, $item_6->barcode);
458 is (defined $datedue6, 1, "Item 2 checked out, due date: ".$datedue6->date_due);
460 my $now = dt_from_string();
461 my $five_weeks = DateTime::Duration->new(weeks => 5);
462 my $five_weeks_ago = $now - $five_weeks;
463 t::lib::Mocks::mock_preference('finesMode', 'production');
465 my $passeddatedue1 = AddIssue($renewing_borrower, $item_7->barcode, $five_weeks_ago);
466 is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: " . $passeddatedue1->date_due);
468 my ( $fine ) = CalcFine( $item_7->unblessed, $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
469 C4::Overdues::UpdateFine(
471 issue_id => $passeddatedue1->id(),
472 itemnumber => $item_7->itemnumber,
473 borrowernumber => $renewing_borrower->{borrowernumber},
474 amount => $fine,
475 due => Koha::DateUtils::output_pref($five_weeks_ago)
479 t::lib::Mocks::mock_preference('RenewalLog', 0);
480 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
481 my %params_renewal = (
482 timestamp => { -like => $date . "%" },
483 module => "CIRCULATION",
484 action => "RENEWAL",
486 my %params_issue = (
487 timestamp => { -like => $date . "%" },
488 module => "CIRCULATION",
489 action => "ISSUE"
491 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );
492 AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
493 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
494 is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
496 t::lib::Mocks::mock_preference('RenewalLog', 1);
497 $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
498 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
499 AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
500 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
501 is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
503 my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
504 is( $fines->count, 2 );
505 is( $fines->next->accounttype, 'F', 'Fine on renewed item is closed out properly' );
506 is( $fines->next->accounttype, 'F', 'Fine on renewed item is closed out properly' );
507 $fines->delete();
510 my $old_issue_log_size = Koha::ActionLogs->count( \%params_issue );
511 my $old_renew_log_size = Koha::ActionLogs->count( \%params_renewal );
512 AddIssue( $renewing_borrower,$item_7->barcode,Koha::DateUtils::output_pref({str=>$datedue6->date_due, dateformat =>'iso'}),0,$date, 0, undef );
513 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
514 is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
515 $new_log_size = Koha::ActionLogs->count( \%params_issue );
516 is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
518 $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
519 $fines->delete();
521 t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
522 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
523 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
524 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
525 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
528 $hold = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next;
529 $hold->cancel;
531 # Bug 14101
532 # Test automatic renewal before value for "norenewalbefore" in policy is set
533 # In this case automatic renewal is not permitted prior to due date
534 my $item_4 = $builder->build_sample_item(
536 biblionumber => $biblio->biblionumber,
537 library => $branch,
538 replacementprice => 16.00,
539 itype => $itemtype,
543 $issue = AddIssue( $renewing_borrower, $item_4->barcode, undef, undef, undef, undef, { auto_renew => 1 } );
544 ( $renewokay, $error ) =
545 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
546 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
547 is( $error, 'auto_too_soon',
548 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
550 # Bug 7413
551 # Test premature manual renewal
552 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7');
554 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
555 is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
556 is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
558 # Bug 14395
559 # Test 'exact time' setting for syspref NoRenewalBeforePrecision
560 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
562 GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
563 $datedue->clone->add( days => -7 ),
564 'Bug 14395: Renewals permitted 7 days before due date, as expected'
567 # Bug 14395
568 # Test 'date' setting for syspref NoRenewalBeforePrecision
569 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
571 GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
572 $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
573 'Bug 14395: Renewals permitted 7 days before due date, as expected'
576 # Bug 14101
577 # Test premature automatic renewal
578 ( $renewokay, $error ) =
579 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
580 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
581 is( $error, 'auto_too_soon',
582 'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
585 # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
586 # and test automatic renewal again
587 $dbh->do('UPDATE issuingrules SET norenewalbefore = 0');
588 ( $renewokay, $error ) =
589 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
590 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
591 is( $error, 'auto_too_soon',
592 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
595 # Change policy so that loans can be renewed 99 days prior to the due date
596 # and test automatic renewal again
597 $dbh->do('UPDATE issuingrules SET norenewalbefore = 99');
598 ( $renewokay, $error ) =
599 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
600 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
601 is( $error, 'auto_renew',
602 'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
605 subtest "too_late_renewal / no_auto_renewal_after" => sub {
606 plan tests => 14;
607 my $item_to_auto_renew = $builder->build(
608 { source => 'Item',
609 value => {
610 biblionumber => $biblio->biblionumber,
611 homebranch => $branch,
612 holdingbranch => $branch,
617 my $ten_days_before = dt_from_string->add( days => -10 );
618 my $ten_days_ahead = dt_from_string->add( days => 10 );
619 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
621 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 9');
622 ( $renewokay, $error ) =
623 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
624 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
625 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
627 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 10');
628 ( $renewokay, $error ) =
629 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
630 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
631 is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
633 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 11');
634 ( $renewokay, $error ) =
635 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
636 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
637 is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
639 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
640 ( $renewokay, $error ) =
641 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
642 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
643 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
645 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = NULL, no_auto_renewal_after_hard_limit = ?', undef, dt_from_string->add( days => -1 ) );
646 ( $renewokay, $error ) =
647 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
648 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
649 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
651 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 15, no_auto_renewal_after_hard_limit = ?', undef, dt_from_string->add( days => -1 ) );
652 ( $renewokay, $error ) =
653 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
654 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
655 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
657 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = NULL, no_auto_renewal_after_hard_limit = ?', undef, dt_from_string->add( days => 1 ) );
658 ( $renewokay, $error ) =
659 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
660 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
661 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
664 subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew" => sub {
665 plan tests => 6;
666 my $item_to_auto_renew = $builder->build({
667 source => 'Item',
668 value => {
669 biblionumber => $biblio->biblionumber,
670 homebranch => $branch,
671 holdingbranch => $branch,
675 my $ten_days_before = dt_from_string->add( days => -10 );
676 my $ten_days_ahead = dt_from_string->add( days => 10 );
677 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
679 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
680 C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
681 C4::Context->set_preference('OPACFineNoRenewals','10');
682 my $fines_amount = 5;
683 my $account = Koha::Account->new({patron_id => $renewing_borrowernumber});
684 $account->add_debit(
686 amount => $fines_amount,
687 type => 'fine',
688 item_id => $item_to_auto_renew->{itemnumber},
689 description => "Some fines"
691 )->accounttype('F')->store;
692 ( $renewokay, $error ) =
693 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
694 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
695 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
697 $account->add_debit(
699 amount => $fines_amount,
700 type => 'fine',
701 item_id => $item_to_auto_renew->{itemnumber},
702 description => "Some fines"
704 )->accounttype('F')->store;
705 ( $renewokay, $error ) =
706 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
707 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
708 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
710 $account->add_debit(
712 amount => $fines_amount,
713 type => 'fine',
714 item_id => $item_to_auto_renew->{itemnumber},
715 description => "Some fines"
717 )->accounttype('F')->store;
718 ( $renewokay, $error ) =
719 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
720 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
721 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
723 $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
726 subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
727 plan tests => 6;
728 my $item_to_auto_renew = $builder->build({
729 source => 'Item',
730 value => {
731 biblionumber => $biblio->biblionumber,
732 homebranch => $branch,
733 holdingbranch => $branch,
737 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
739 my $ten_days_before = dt_from_string->add( days => -10 );
740 my $ten_days_ahead = dt_from_string->add( days => 10 );
742 # Patron is expired and BlockExpiredPatronOpacActions=0
743 # => auto renew is allowed
744 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
745 my $patron = $expired_borrower;
746 my $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
747 ( $renewokay, $error ) =
748 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
749 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
750 is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
751 Koha::Checkouts->find( $checkout->issue_id )->delete;
754 # Patron is expired and BlockExpiredPatronOpacActions=1
755 # => auto renew is not allowed
756 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
757 $patron = $expired_borrower;
758 $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
759 ( $renewokay, $error ) =
760 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
761 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
762 is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
763 Koha::Checkouts->find( $checkout->issue_id )->delete;
766 # Patron is not expired and BlockExpiredPatronOpacActions=1
767 # => auto renew is allowed
768 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
769 $patron = $renewing_borrower;
770 $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
771 ( $renewokay, $error ) =
772 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
773 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
774 is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
775 Koha::Checkouts->find( $checkout->issue_id )->delete;
778 subtest "GetLatestAutoRenewDate" => sub {
779 plan tests => 5;
780 my $item_to_auto_renew = $builder->build(
781 { source => 'Item',
782 value => {
783 biblionumber => $biblio->biblionumber,
784 homebranch => $branch,
785 holdingbranch => $branch,
790 my $ten_days_before = dt_from_string->add( days => -10 );
791 my $ten_days_ahead = dt_from_string->add( days => 10 );
792 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
793 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = NULL, no_auto_renewal_after_hard_limit = NULL');
794 my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
795 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' );
796 my $five_days_before = dt_from_string->add( days => -5 );
797 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 5, no_auto_renewal_after_hard_limit = NULL');
798 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
799 is( $latest_auto_renew_date->truncate( to => 'minute' ),
800 $five_days_before->truncate( to => 'minute' ),
801 'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
803 my $five_days_ahead = dt_from_string->add( days => 5 );
804 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 15, no_auto_renewal_after_hard_limit = NULL');
805 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
806 is( $latest_auto_renew_date->truncate( to => 'minute' ),
807 $five_days_ahead->truncate( to => 'minute' ),
808 'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
810 my $two_days_ahead = dt_from_string->add( days => 2 );
811 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = NULL, no_auto_renewal_after_hard_limit = ?', undef, dt_from_string->add( days => 2 ) );
812 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
813 is( $latest_auto_renew_date->truncate( to => 'day' ),
814 $two_days_ahead->truncate( to => 'day' ),
815 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
817 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 15, no_auto_renewal_after_hard_limit = ?', undef, dt_from_string->add( days => 2 ) );
818 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
819 is( $latest_auto_renew_date->truncate( to => 'day' ),
820 $two_days_ahead->truncate( to => 'day' ),
821 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
826 # Too many renewals
828 # set policy to forbid renewals
829 $dbh->do('UPDATE issuingrules SET norenewalbefore = NULL, renewalsallowed = 0');
831 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
832 is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
833 is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
835 # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
836 t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
837 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
839 C4::Overdues::UpdateFine(
841 issue_id => $issue->id(),
842 itemnumber => $item_1->itemnumber,
843 borrowernumber => $renewing_borrower->{borrowernumber},
844 amount => 15.00,
845 type => q{},
846 due => Koha::DateUtils::output_pref($datedue)
850 my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower->{borrowernumber} })->next();
851 is( $line->accounttype, 'FU', 'Account line type is FU' );
852 is( $line->lastincrement, '15.000000', 'Account line last increment is 15.00' );
853 is( $line->amountoutstanding, '15.000000', 'Account line amount outstanding is 15.00' );
854 is( $line->amount, '15.000000', 'Account line amount is 15.00' );
855 is( $line->issue_id, $issue->id, 'Account line issue id matches' );
857 my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
858 is( $offset->type, 'Fine', 'Account offset type is Fine' );
859 is( $offset->amount, '15.000000', 'Account offset amount is 15.00' );
861 t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
862 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
864 LostItem( $item_1->itemnumber, 'test', 1 );
866 $line = Koha::Account::Lines->find($line->id);
867 is( $line->accounttype, 'F', 'Account type correctly changed from FU to F' );
869 my $item = Koha::Items->find($item_1->itemnumber);
870 ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
871 my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
872 is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
874 my $total_due = $dbh->selectrow_array(
875 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
876 undef, $renewing_borrower->{borrowernumber}
879 is( $total_due, '15.000000', 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
881 C4::Context->dbh->do("DELETE FROM accountlines");
883 C4::Overdues::UpdateFine(
885 issue_id => $issue2->id(),
886 itemnumber => $item_2->itemnumber,
887 borrowernumber => $renewing_borrower->{borrowernumber},
888 amount => 15.00,
889 type => q{},
890 due => Koha::DateUtils::output_pref($datedue)
894 LostItem( $item_2->itemnumber, 'test', 0 );
896 my $item2 = Koha::Items->find($item_2->itemnumber);
897 ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
898 ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
900 $total_due = $dbh->selectrow_array(
901 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
902 undef, $renewing_borrower->{borrowernumber}
905 ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
907 my $future = dt_from_string();
908 $future->add( days => 7 );
909 my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
910 ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
912 # Users cannot renew any item if there is an overdue item
913 t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
914 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
915 is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
916 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
917 is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
919 my $manager = $builder->build_object({ class => "Koha::Patrons" });
920 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
921 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
922 $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
923 LostItem( $item_3->itemnumber, 'test', 0 );
924 my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
925 is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
929 # GetUpcomingDueIssues tests
930 my $branch = $library2->{branchcode};
932 #Create another record
933 my $biblio2 = $builder->build_sample_biblio();
935 #Create third item
936 my $item_1 = Koha::Items->find($reused_itemnumber_1);
937 my $item_2 = Koha::Items->find($reused_itemnumber_2);
938 my $item_3 = $builder->build_sample_item(
940 biblionumber => $biblio2->biblionumber,
941 library => $branch,
942 itype => $itemtype,
947 # Create a borrower
948 my %a_borrower_data = (
949 firstname => 'Fridolyn',
950 surname => 'SOMERS',
951 categorycode => $patron_category->{categorycode},
952 branchcode => $branch,
955 my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
956 my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
958 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
959 my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
960 my $today = DateTime->today(time_zone => C4::Context->tz());
962 my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
963 my $datedue = dt_from_string( $issue->date_due() );
964 my $issue2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
965 my $datedue2 = dt_from_string( $issue->date_due() );
967 my $upcoming_dues;
969 # GetUpcomingDueIssues tests
970 for my $i(0..1) {
971 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
972 is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
975 #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
976 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
977 is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
979 for my $i(3..5) {
980 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
981 is ( scalar( @$upcoming_dues ), 1,
982 "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
985 # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
987 my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
989 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
990 is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
992 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
993 is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
995 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
996 is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
998 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
999 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1001 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1002 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1004 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1005 is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1010 my $branch = $library2->{branchcode};
1012 my $biblio = $builder->build_sample_biblio();
1014 #Create third item
1015 my $item = $builder->build_sample_item(
1017 biblionumber => $biblio->biblionumber,
1018 library => $branch,
1019 itype => $itemtype,
1023 # Create a borrower
1024 my %a_borrower_data = (
1025 firstname => 'Kyle',
1026 surname => 'Hall',
1027 categorycode => $patron_category->{categorycode},
1028 branchcode => $branch,
1031 my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1033 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1034 my $issue = AddIssue( $borrower, $item->barcode );
1035 UpdateFine(
1037 issue_id => $issue->id(),
1038 itemnumber => $item->itemnumber,
1039 borrowernumber => $borrowernumber,
1040 amount => 0,
1041 type => q{}
1045 my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1046 my $count = $hr->{count};
1048 is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1052 $dbh->do('DELETE FROM issues');
1053 $dbh->do('DELETE FROM items');
1054 $dbh->do('DELETE FROM issuingrules');
1055 Koha::CirculationRules->search()->delete();
1056 $dbh->do(
1058 INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, issuelength, lengthunit, renewalsallowed, renewalperiod,
1059 norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
1062 '*', '*', '*', 25,
1063 14, 'days',
1064 1, 7,
1065 undef, 0,
1066 .10, 1
1068 Koha::CirculationRules->set_rules(
1070 categorycode => '*',
1071 itemtype => '*',
1072 branchcode => '*',
1073 rules => {
1074 maxissueqty => 20
1078 my $biblio = $builder->build_sample_biblio();
1080 my $item_1 = $builder->build_sample_item(
1082 biblionumber => $biblio->biblionumber,
1083 library => $library2->{branchcode},
1084 itype => $itemtype,
1088 my $item_2= $builder->build_sample_item(
1090 biblionumber => $biblio->biblionumber,
1091 library => $library2->{branchcode},
1092 itype => $itemtype,
1096 my $borrowernumber1 = Koha::Patron->new({
1097 firstname => 'Kyle',
1098 surname => 'Hall',
1099 categorycode => $patron_category->{categorycode},
1100 branchcode => $library2->{branchcode},
1101 })->store->borrowernumber;
1102 my $borrowernumber2 = Koha::Patron->new({
1103 firstname => 'Chelsea',
1104 surname => 'Hall',
1105 categorycode => $patron_category->{categorycode},
1106 branchcode => $library2->{branchcode},
1107 })->store->borrowernumber;
1109 my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1110 my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1112 my $issue = AddIssue( $borrower1, $item_1->barcode );
1114 my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1115 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1117 AddReserve(
1118 $library2->{branchcode}, $borrowernumber2, $biblio->biblionumber,
1119 '', 1, undef, undef, '',
1120 undef, undef, undef
1123 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1124 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1125 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1126 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1128 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1129 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1130 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1131 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1133 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1134 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1135 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1136 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1138 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1139 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1140 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1141 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1143 # Setting item not checked out to be not for loan but holdable
1144 ModItem({ notforloan => -1 }, $biblio->biblionumber, $item_2->itemnumber);
1146 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1147 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' );
1151 # Don't allow renewing onsite checkout
1152 my $branch = $library->{branchcode};
1154 #Create another record
1155 my $biblio = $builder->build_sample_biblio();
1157 my $item = $builder->build_sample_item(
1159 biblionumber => $biblio->biblionumber,
1160 library => $branch,
1161 itype => $itemtype,
1165 my $borrowernumber = Koha::Patron->new({
1166 firstname => 'fn',
1167 surname => 'dn',
1168 categorycode => $patron_category->{categorycode},
1169 branchcode => $branch,
1170 })->store->borrowernumber;
1172 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1174 my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1175 my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $item->itemnumber );
1176 is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1177 is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1181 my $library = $builder->build({ source => 'Branch' });
1183 my $biblio = $builder->build_sample_biblio();
1185 my $item = $builder->build_sample_item(
1187 biblionumber => $biblio->biblionumber,
1188 library => $library->{branchcode},
1189 itype => $itemtype,
1193 my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1195 my $issue = AddIssue( $patron, $item->barcode );
1196 UpdateFine(
1198 issue_id => $issue->id(),
1199 itemnumber => $item->itemnumber,
1200 borrowernumber => $patron->{borrowernumber},
1201 amount => 1,
1202 type => q{}
1205 UpdateFine(
1207 issue_id => $issue->id(),
1208 itemnumber => $item->itemnumber,
1209 borrowernumber => $patron->{borrowernumber},
1210 amount => 2,
1211 type => q{}
1214 is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1217 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1218 plan tests => 24;
1220 my $homebranch = $builder->build( { source => 'Branch' } );
1221 my $holdingbranch = $builder->build( { source => 'Branch' } );
1222 my $otherbranch = $builder->build( { source => 'Branch' } );
1223 my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1224 my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1226 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1227 my $item = $builder->build(
1228 { source => 'Item',
1229 value => {
1230 homebranch => $homebranch->{branchcode},
1231 holdingbranch => $holdingbranch->{branchcode},
1232 biblionumber => $biblioitem->{biblionumber}
1237 set_userenv($holdingbranch);
1239 my $issue = AddIssue( $patron_1->unblessed, $item->{barcode} );
1240 is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
1242 my ( $error, $question, $alerts );
1244 # AllowReturnToBranch == anywhere
1245 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1246 ## Test that unknown barcodes don't generate internal server errors
1247 set_userenv($homebranch);
1248 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1249 ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1250 ## Can be issued from homebranch
1251 set_userenv($homebranch);
1252 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1253 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1254 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1255 ## Can be issued from holdingbranch
1256 set_userenv($holdingbranch);
1257 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1258 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1259 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1260 ## Can be issued from another branch
1261 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1262 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1263 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1265 # AllowReturnToBranch == holdingbranch
1266 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1267 ## Cannot be issued from homebranch
1268 set_userenv($homebranch);
1269 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1270 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1271 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1272 is( $error->{branch_to_return}, $holdingbranch->{branchcode} );
1273 ## Can be issued from holdinbranch
1274 set_userenv($holdingbranch);
1275 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1276 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1277 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1278 ## Cannot be issued from another branch
1279 set_userenv($otherbranch);
1280 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1281 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1282 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1283 is( $error->{branch_to_return}, $holdingbranch->{branchcode} );
1285 # AllowReturnToBranch == homebranch
1286 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1287 ## Can be issued from holdinbranch
1288 set_userenv($homebranch);
1289 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1290 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1291 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1292 ## Cannot be issued from holdinbranch
1293 set_userenv($holdingbranch);
1294 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1295 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1296 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1297 is( $error->{branch_to_return}, $homebranch->{branchcode} );
1298 ## Cannot be issued from holdinbranch
1299 set_userenv($otherbranch);
1300 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1301 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1302 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1303 is( $error->{branch_to_return}, $homebranch->{branchcode} );
1305 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1308 subtest 'AddIssue & AllowReturnToBranch' => sub {
1309 plan tests => 9;
1311 my $homebranch = $builder->build( { source => 'Branch' } );
1312 my $holdingbranch = $builder->build( { source => 'Branch' } );
1313 my $otherbranch = $builder->build( { source => 'Branch' } );
1314 my $patron_1 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1315 my $patron_2 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1317 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1318 my $item = $builder->build(
1319 { source => 'Item',
1320 value => {
1321 homebranch => $homebranch->{branchcode},
1322 holdingbranch => $holdingbranch->{branchcode},
1323 notforloan => 0,
1324 itemlost => 0,
1325 withdrawn => 0,
1326 biblionumber => $biblioitem->{biblionumber}
1331 set_userenv($holdingbranch);
1333 my $ref_issue = 'Koha::Checkout';
1334 my $issue = AddIssue( $patron_1, $item->{barcode} );
1336 my ( $error, $question, $alerts );
1338 # AllowReturnToBranch == homebranch
1339 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1340 ## Can be issued from homebranch
1341 set_userenv($homebranch);
1342 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1343 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1344 ## Can be issued from holdinbranch
1345 set_userenv($holdingbranch);
1346 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1347 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1348 ## Can be issued from another branch
1349 set_userenv($otherbranch);
1350 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1351 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1353 # AllowReturnToBranch == holdinbranch
1354 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1355 ## Cannot be issued from homebranch
1356 set_userenv($homebranch);
1357 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1358 ## Can be issued from holdingbranch
1359 set_userenv($holdingbranch);
1360 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1361 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1362 ## Cannot be issued from another branch
1363 set_userenv($otherbranch);
1364 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1366 # AllowReturnToBranch == homebranch
1367 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1368 ## Can be issued from homebranch
1369 set_userenv($homebranch);
1370 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1371 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1372 ## Cannot be issued from holdinbranch
1373 set_userenv($holdingbranch);
1374 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1375 ## Cannot be issued from another branch
1376 set_userenv($otherbranch);
1377 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1378 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1381 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1382 plan tests => 8;
1384 my $library = $builder->build( { source => 'Branch' } );
1385 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1387 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1388 my $item_1 = $builder->build(
1389 { source => 'Item',
1390 value => {
1391 homebranch => $library->{branchcode},
1392 holdingbranch => $library->{branchcode},
1393 biblionumber => $biblioitem_1->{biblionumber}
1397 my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1398 my $item_2 = $builder->build(
1399 { source => 'Item',
1400 value => {
1401 homebranch => $library->{branchcode},
1402 holdingbranch => $library->{branchcode},
1403 biblionumber => $biblioitem_2->{biblionumber}
1408 my ( $error, $question, $alerts );
1410 # Patron cannot issue item_1, they have overdues
1411 my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1412 my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, $yesterday ); # Add an overdue
1414 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1415 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1416 is( keys(%$error) + keys(%$alerts), 0, 'No key for error and alert' . str($error, $question, $alerts) );
1417 is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
1419 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1420 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1421 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1422 is( $error->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
1424 # Patron cannot issue item_1, they are debarred
1425 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1426 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
1427 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1428 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1429 is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
1431 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
1432 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1433 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1434 is( $error->{USERBLOCKEDNOENDDATE}, '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
1437 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
1438 plan tests => 1;
1440 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1441 my $patron_category_x = $builder->build_object(
1443 class => 'Koha::Patron::Categories',
1444 value => { category_type => 'X' }
1447 my $patron = $builder->build_object(
1449 class => 'Koha::Patrons',
1450 value => {
1451 categorycode => $patron_category_x->categorycode,
1452 gonenoaddress => undef,
1453 lost => undef,
1454 debarred => undef,
1455 borrowernotes => ""
1459 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1460 my $item_1 = $builder->build(
1462 source => 'Item',
1463 value => {
1464 homebranch => $library->branchcode,
1465 holdingbranch => $library->branchcode,
1466 biblionumber => $biblioitem_1->{biblionumber}
1471 my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->{barcode} );
1472 is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
1474 # TODO There are other tests to provide here
1477 subtest 'MultipleReserves' => sub {
1478 plan tests => 3;
1480 my $biblio = $builder->build_sample_biblio();
1482 my $branch = $library2->{branchcode};
1484 my $item_1 = $builder->build_sample_item(
1486 biblionumber => $biblio->biblionumber,
1487 library => $branch,
1488 replacementprice => 12.00,
1489 itype => $itemtype,
1493 my $item_2 = $builder->build_sample_item(
1495 biblionumber => $biblio->biblionumber,
1496 library => $branch,
1497 replacementprice => 12.00,
1498 itype => $itemtype,
1502 my $bibitems = '';
1503 my $priority = '1';
1504 my $resdate = undef;
1505 my $expdate = undef;
1506 my $notes = '';
1507 my $checkitem = undef;
1508 my $found = undef;
1510 my %renewing_borrower_data = (
1511 firstname => 'John',
1512 surname => 'Renewal',
1513 categorycode => $patron_category->{categorycode},
1514 branchcode => $branch,
1516 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
1517 my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
1518 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
1519 my $datedue = dt_from_string( $issue->date_due() );
1520 is (defined $issue->date_due(), 1, "item 1 checked out");
1521 my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
1523 my %reserving_borrower_data1 = (
1524 firstname => 'Katrin',
1525 surname => 'Reservation',
1526 categorycode => $patron_category->{categorycode},
1527 branchcode => $branch,
1529 my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
1530 AddReserve(
1531 $branch, $reserving_borrowernumber1, $biblio->biblionumber,
1532 $bibitems, $priority, $resdate, $expdate, $notes,
1533 'a title', $checkitem, $found
1536 my %reserving_borrower_data2 = (
1537 firstname => 'Kirk',
1538 surname => 'Reservation',
1539 categorycode => $patron_category->{categorycode},
1540 branchcode => $branch,
1542 my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
1543 AddReserve(
1544 $branch, $reserving_borrowernumber2, $biblio->biblionumber,
1545 $bibitems, $priority, $resdate, $expdate, $notes,
1546 'a title', $checkitem, $found
1550 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1551 is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
1554 my $item_3 = $builder->build_sample_item(
1556 biblionumber => $biblio->biblionumber,
1557 library => $branch,
1558 replacementprice => 12.00,
1559 itype => $itemtype,
1564 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1565 is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
1569 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
1570 plan tests => 5;
1572 my $library = $builder->build( { source => 'Branch' } );
1573 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1575 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1576 my $biblionumber = $biblioitem->{biblionumber};
1577 my $item_1 = $builder->build(
1578 { source => 'Item',
1579 value => {
1580 homebranch => $library->{branchcode},
1581 holdingbranch => $library->{branchcode},
1582 biblionumber => $biblionumber,
1586 my $item_2 = $builder->build(
1587 { source => 'Item',
1588 value => {
1589 homebranch => $library->{branchcode},
1590 holdingbranch => $library->{branchcode},
1591 biblionumber => $biblionumber,
1596 my ( $error, $question, $alerts );
1597 my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, dt_from_string->add( days => 1 ) );
1599 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1600 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1601 is( keys(%$error) + keys(%$alerts), 0, 'No error or alert should be raised' . str($error, $question, $alerts) );
1602 is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' . str($error, $question, $alerts) );
1604 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1605 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1606 is( keys(%$error) + keys(%$question) + keys(%$alerts), 0, 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1' . str($error, $question, $alerts) );
1608 # Add a subscription
1609 Koha::Subscription->new({ biblionumber => $biblionumber })->store;
1611 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1612 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1613 is( keys(%$error) + keys(%$question) + keys(%$alerts), 0, 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription' . str($error, $question, $alerts) );
1615 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1616 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1617 is( keys(%$error) + keys(%$question) + keys(%$alerts), 0, 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription' . str($error, $question, $alerts) );
1620 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
1621 plan tests => 8;
1623 my $library = $builder->build( { source => 'Branch' } );
1624 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1626 # Add 2 items
1627 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1628 my $item_1 = $builder->build(
1630 source => 'Item',
1631 value => {
1632 homebranch => $library->{branchcode},
1633 holdingbranch => $library->{branchcode},
1634 notforloan => 0,
1635 itemlost => 0,
1636 withdrawn => 0,
1637 biblionumber => $biblioitem_1->{biblionumber}
1641 my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1642 my $item_2 = $builder->build(
1644 source => 'Item',
1645 value => {
1646 homebranch => $library->{branchcode},
1647 holdingbranch => $library->{branchcode},
1648 notforloan => 0,
1649 itemlost => 0,
1650 withdrawn => 0,
1651 biblionumber => $biblioitem_2->{biblionumber}
1656 # And the issuing rule
1657 Koha::IssuingRules->search->delete;
1658 my $rule = Koha::IssuingRule->new(
1660 categorycode => '*',
1661 itemtype => '*',
1662 branchcode => '*',
1663 issuelength => 1,
1664 firstremind => 1, # 1 day of grace
1665 finedays => 2, # 2 days of fine per day of overdue
1666 lengthunit => 'days',
1669 $rule->store();
1671 # Patron cannot issue item_1, they have overdues
1672 my $five_days_ago = dt_from_string->subtract( days => 5 );
1673 my $ten_days_ago = dt_from_string->subtract( days => 10 );
1674 AddIssue( $patron, $item_1->{barcode}, $five_days_ago ); # Add an overdue
1675 AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1676 ; # Add another overdue
1678 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
1679 AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, dt_from_string );
1680 my $debarments = Koha::Patron::Debarments::GetDebarments(
1681 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1682 is( scalar(@$debarments), 1 );
1684 # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
1685 # Same for the others
1686 my $expected_expiration = output_pref(
1688 dt => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1689 dateformat => 'sql',
1690 dateonly => 1
1693 is( $debarments->[0]->{expiration}, $expected_expiration );
1695 AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, dt_from_string );
1696 $debarments = Koha::Patron::Debarments::GetDebarments(
1697 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1698 is( scalar(@$debarments), 1 );
1699 $expected_expiration = output_pref(
1701 dt => dt_from_string->add( days => ( 10 - 1 ) * 2 ),
1702 dateformat => 'sql',
1703 dateonly => 1
1706 is( $debarments->[0]->{expiration}, $expected_expiration );
1708 Koha::Patron::Debarments::DelUniqueDebarment(
1709 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1711 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
1712 AddIssue( $patron, $item_1->{barcode}, $five_days_ago ); # Add an overdue
1713 AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1714 ; # Add another overdue
1715 AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, dt_from_string );
1716 $debarments = Koha::Patron::Debarments::GetDebarments(
1717 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1718 is( scalar(@$debarments), 1 );
1719 $expected_expiration = output_pref(
1721 dt => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1722 dateformat => 'sql',
1723 dateonly => 1
1726 is( $debarments->[0]->{expiration}, $expected_expiration );
1728 AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, dt_from_string );
1729 $debarments = Koha::Patron::Debarments::GetDebarments(
1730 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1731 is( scalar(@$debarments), 1 );
1732 $expected_expiration = output_pref(
1734 dt => dt_from_string->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
1735 dateformat => 'sql',
1736 dateonly => 1
1739 is( $debarments->[0]->{expiration}, $expected_expiration );
1742 subtest 'AddReturn + suspension_chargeperiod' => sub {
1743 plan tests => 21;
1745 my $library = $builder->build( { source => 'Branch' } );
1746 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1748 # Add 2 items
1749 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1750 my $item_1 = $builder->build(
1752 source => 'Item',
1753 value => {
1754 homebranch => $library->{branchcode},
1755 holdingbranch => $library->{branchcode},
1756 notforloan => 0,
1757 itemlost => 0,
1758 withdrawn => 0,
1759 biblionumber => $biblioitem_1->{biblionumber}
1764 # And the issuing rule
1765 Koha::IssuingRules->search->delete;
1766 my $rule = Koha::IssuingRule->new(
1768 categorycode => '*',
1769 itemtype => '*',
1770 branchcode => '*',
1771 issuelength => 1,
1772 firstremind => 0, # 0 day of grace
1773 finedays => 2, # 2 days of fine per day of overdue
1774 suspension_chargeperiod => 1,
1775 lengthunit => 'days',
1778 $rule->store();
1780 my $five_days_ago = dt_from_string->subtract( days => 5 );
1781 # We want to charge 2 days every day, without grace
1782 # With 5 days of overdue: 5 * Z
1783 my $expected_expiration = dt_from_string->add( days => ( 5 * 2 ) / 1 );
1784 test_debarment_on_checkout(
1786 item => $item_1,
1787 library => $library,
1788 patron => $patron,
1789 due_date => $five_days_ago,
1790 expiration_date => $expected_expiration,
1794 # We want to charge 2 days every 2 days, without grace
1795 # With 5 days of overdue: (5 * 2) / 2
1796 $rule->suspension_chargeperiod(2)->store;
1797 $expected_expiration = dt_from_string->add( days => floor( 5 * 2 ) / 2 );
1798 test_debarment_on_checkout(
1800 item => $item_1,
1801 library => $library,
1802 patron => $patron,
1803 due_date => $five_days_ago,
1804 expiration_date => $expected_expiration,
1808 # We want to charge 2 days every 3 days, with 1 day of grace
1809 # With 5 days of overdue: ((5-1) / 3 ) * 2
1810 $rule->suspension_chargeperiod(3)->store;
1811 $rule->firstremind(1)->store;
1812 $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
1813 test_debarment_on_checkout(
1815 item => $item_1,
1816 library => $library,
1817 patron => $patron,
1818 due_date => $five_days_ago,
1819 expiration_date => $expected_expiration,
1823 # Use finesCalendar to know if holiday must be skipped to calculate the due date
1824 # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
1825 $rule->finedays(2)->store;
1826 $rule->suspension_chargeperiod(1)->store;
1827 $rule->firstremind(0)->store;
1828 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
1830 # Adding a holiday 2 days ago
1831 my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
1832 my $two_days_ago = dt_from_string->subtract( days => 2 );
1833 $calendar->insert_single_holiday(
1834 day => $two_days_ago->day,
1835 month => $two_days_ago->month,
1836 year => $two_days_ago->year,
1837 title => 'holidayTest-2d',
1838 description => 'holidayDesc 2 days ago'
1840 # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
1841 $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
1842 test_debarment_on_checkout(
1844 item => $item_1,
1845 library => $library,
1846 patron => $patron,
1847 due_date => $five_days_ago,
1848 expiration_date => $expected_expiration,
1852 # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
1853 my $two_days_ahead = dt_from_string->add( days => 2 );
1854 $calendar->insert_single_holiday(
1855 day => $two_days_ahead->day,
1856 month => $two_days_ahead->month,
1857 year => $two_days_ahead->year,
1858 title => 'holidayTest+2d',
1859 description => 'holidayDesc 2 days ahead'
1862 # Same as above, but we should skip D+2
1863 $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
1864 test_debarment_on_checkout(
1866 item => $item_1,
1867 library => $library,
1868 patron => $patron,
1869 due_date => $five_days_ago,
1870 expiration_date => $expected_expiration,
1874 # Adding another holiday, day of expiration date
1875 my $expected_expiration_dt = dt_from_string($expected_expiration);
1876 $calendar->insert_single_holiday(
1877 day => $expected_expiration_dt->day,
1878 month => $expected_expiration_dt->month,
1879 year => $expected_expiration_dt->year,
1880 title => 'holidayTest_exp',
1881 description => 'holidayDesc on expiration date'
1883 # Expiration date will be the day after
1884 test_debarment_on_checkout(
1886 item => $item_1,
1887 library => $library,
1888 patron => $patron,
1889 due_date => $five_days_ago,
1890 expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
1894 test_debarment_on_checkout(
1896 item => $item_1,
1897 library => $library,
1898 patron => $patron,
1899 return_date => dt_from_string->add(days => 5),
1900 expiration_date => dt_from_string->add(days => 5 + (5 * 2 - 1) ),
1905 subtest 'AddReturn | is_overdue' => sub {
1906 plan tests => 5;
1908 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
1909 t::lib::Mocks::mock_preference('finesMode', 'production');
1910 t::lib::Mocks::mock_preference('MaxFine', '100');
1912 my $library = $builder->build( { source => 'Branch' } );
1913 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1915 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1916 my $item = $builder->build(
1918 source => 'Item',
1919 value => {
1920 homebranch => $library->{branchcode},
1921 holdingbranch => $library->{branchcode},
1922 notforloan => 0,
1923 itemlost => 0,
1924 withdrawn => 0,
1925 biblionumber => $biblioitem->{biblionumber},
1930 Koha::IssuingRules->search->delete;
1931 my $rule = Koha::IssuingRule->new(
1933 categorycode => '*',
1934 itemtype => '*',
1935 branchcode => '*',
1936 issuelength => 6,
1937 lengthunit => 'days',
1938 fine => 1, # Charge 1 every day of overdue
1939 chargeperiod => 1,
1942 $rule->store();
1944 my $one_day_ago = dt_from_string->subtract( days => 1 );
1945 my $five_days_ago = dt_from_string->subtract( days => 5 );
1946 my $ten_days_ago = dt_from_string->subtract( days => 10 );
1947 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1949 # No date specify, today will be used
1950 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1951 AddReturn( $item->{barcode}, $library->{branchcode} );
1952 is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
1953 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1955 # specify return date 5 days before => no overdue
1956 AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
1957 AddReturn( $item->{barcode}, $library->{branchcode}, undef, $ten_days_ago );
1958 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
1959 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1961 # specify return date 5 days later => overdue
1962 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1963 AddReturn( $item->{barcode}, $library->{branchcode}, undef, $five_days_ago );
1964 is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
1965 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1967 # specify dropbox date 5 days before => no overdue
1968 AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
1969 AddReturn( $item->{barcode}, $library->{branchcode}, $ten_days_ago );
1970 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
1971 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1973 # specify dropbox date 5 days later => overdue, or... not
1974 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1975 AddReturn( $item->{barcode}, $library->{branchcode}, $five_days_ago );
1976 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue in dropbox mode' ); # FIXME? This is weird, the FU fine is created ( _CalculateAndUpdateFine > C4::Overdues::UpdateFine ) then remove later (in _FixOverduesOnReturn). Looks like it is a feature
1977 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1980 subtest '_FixAccountForLostAndReturned' => sub {
1982 plan tests => 5;
1984 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
1985 t::lib::Mocks::mock_preference( 'WhenLostForgiveFine', 0 );
1987 my $processfee_amount = 20;
1988 my $replacement_amount = 99.00;
1989 my $item_type = $builder->build_object(
1990 { class => 'Koha::ItemTypes',
1991 value => {
1992 notforloan => undef,
1993 rentalcharge => 0,
1994 defaultreplacecost => undef,
1995 processfee => $processfee_amount,
1996 rentalcharge_daily => 0,
2000 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2002 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Daria' });
2004 subtest 'Full write-off tests' => sub {
2006 plan tests => 10;
2008 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2009 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2010 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
2012 my $item = $builder->build_sample_item(
2014 biblionumber => $biblio->biblionumber,
2015 library => $library->branchcode,
2016 replacementprice => $replacement_amount,
2017 itype => $item_type->itemtype,
2021 AddIssue( $patron->unblessed, $item->barcode );
2023 # Simulate item marked as lost
2024 ModItem( { itemlost => 3 }, $biblio->biblionumber, $item->itemnumber );
2025 LostItem( $item->itemnumber, 1 );
2027 my $processing_fee_lines = Koha::Account::Lines->search(
2028 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2029 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2030 my $processing_fee_line = $processing_fee_lines->next;
2031 is( $processing_fee_line->amount + 0,
2032 $processfee_amount, 'The right PF amount is generated' );
2033 is( $processing_fee_line->amountoutstanding + 0,
2034 $processfee_amount, 'The right PF amountoutstanding is generated' );
2036 my $lost_fee_lines = Koha::Account::Lines->search(
2037 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2038 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2039 my $lost_fee_line = $lost_fee_lines->next;
2040 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2041 is( $lost_fee_line->amountoutstanding + 0,
2042 $replacement_amount, 'The right L amountoutstanding is generated' );
2044 my $account = $patron->account;
2045 my $debts = $account->outstanding_debits;
2047 # Write off the debt
2048 my $credit = $account->add_credit(
2049 { amount => $account->balance,
2050 type => 'writeoff'
2053 $credit->apply( { debits => $debts, offset_type => 'Writeoff' } );
2055 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2056 is( $credit_return_id, undef, 'No CR account line added' );
2058 $lost_fee_line->discard_changes; # reload from DB
2059 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2060 is( $lost_fee_line->accounttype,
2061 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2063 is( $patron->account->balance, -0, 'The patron balance is 0, everything was written off' );
2066 subtest 'Full payment tests' => sub {
2068 plan tests => 12;
2070 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2072 my $item = $builder->build_sample_item(
2074 biblionumber => $biblio->biblionumber,
2075 library => $library->branchcode,
2076 replacementprice => $replacement_amount,
2077 itype => $item_type->itemtype
2081 AddIssue( $patron->unblessed, $item->barcode );
2083 # Simulate item marked as lost
2084 ModItem( { itemlost => 1 }, $biblio->biblionumber, $item->itemnumber );
2085 LostItem( $item->itemnumber, 1 );
2087 my $processing_fee_lines = Koha::Account::Lines->search(
2088 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2089 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2090 my $processing_fee_line = $processing_fee_lines->next;
2091 is( $processing_fee_line->amount + 0,
2092 $processfee_amount, 'The right PF amount is generated' );
2093 is( $processing_fee_line->amountoutstanding + 0,
2094 $processfee_amount, 'The right PF amountoutstanding is generated' );
2096 my $lost_fee_lines = Koha::Account::Lines->search(
2097 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2098 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2099 my $lost_fee_line = $lost_fee_lines->next;
2100 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2101 is( $lost_fee_line->amountoutstanding + 0,
2102 $replacement_amount, 'The right L amountountstanding is generated' );
2104 my $account = $patron->account;
2105 my $debts = $account->outstanding_debits;
2107 # Write off the debt
2108 my $credit = $account->add_credit(
2109 { amount => $account->balance,
2110 type => 'payment'
2113 $credit->apply( { debits => $debts, offset_type => 'Payment' } );
2115 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2116 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2118 is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2119 is( $credit_return->amount + 0,
2120 -99.00, 'The account line of type CR has an amount of -99' );
2121 is( $credit_return->amountoutstanding + 0,
2122 -99.00, 'The account line of type CR has an amountoutstanding of -99' );
2124 $lost_fee_line->discard_changes;
2125 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2126 is( $lost_fee_line->accounttype,
2127 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2129 is( $patron->account->balance,
2130 -99, 'The patron balance is -99, a credit that equals the lost fee payment' );
2133 subtest 'Test without payment or write off' => sub {
2135 plan tests => 12;
2137 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2139 my $item = $builder->build_sample_item(
2141 biblionumber => $biblio->biblionumber,
2142 library => $library->branchcode,
2143 replacementprice => 23.00,
2144 replacementprice => $replacement_amount,
2145 itype => $item_type->itemtype
2149 AddIssue( $patron->unblessed, $item->barcode );
2151 # Simulate item marked as lost
2152 ModItem( { itemlost => 3 }, $biblio->biblionumber, $item->itemnumber );
2153 LostItem( $item->itemnumber, 1 );
2155 my $processing_fee_lines = Koha::Account::Lines->search(
2156 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2157 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2158 my $processing_fee_line = $processing_fee_lines->next;
2159 is( $processing_fee_line->amount + 0,
2160 $processfee_amount, 'The right PF amount is generated' );
2161 is( $processing_fee_line->amountoutstanding + 0,
2162 $processfee_amount, 'The right PF amountoutstanding is generated' );
2164 my $lost_fee_lines = Koha::Account::Lines->search(
2165 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2166 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2167 my $lost_fee_line = $lost_fee_lines->next;
2168 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2169 is( $lost_fee_line->amountoutstanding + 0,
2170 $replacement_amount, 'The right L amountountstanding is generated' );
2172 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2173 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2175 is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2176 is( $credit_return->amount + 0, -99.00, 'The account line of type CR has an amount of -99' );
2177 is( $credit_return->amountoutstanding + 0, 0, 'The account line of type CR has an amountoutstanding of 0' );
2179 $lost_fee_line->discard_changes;
2180 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2181 is( $lost_fee_line->accounttype, 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2183 is( $patron->account->balance, 20, 'The patron balance is 20, still owes the processing fee' );
2186 subtest 'Test with partial payement and write off, and remaining debt' => sub {
2188 plan tests => 15;
2190 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2191 my $item = $builder->build_sample_item(
2193 biblionumber => $biblio->biblionumber,
2194 library => $library->branchcode,
2195 replacementprice => $replacement_amount,
2196 itype => $item_type->itemtype
2200 AddIssue( $patron->unblessed, $item->barcode );
2202 # Simulate item marked as lost
2203 ModItem( { itemlost => 1 }, $biblio->biblionumber, $item->itemnumber );
2204 LostItem( $item->itemnumber, 1 );
2206 my $processing_fee_lines = Koha::Account::Lines->search(
2207 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2208 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2209 my $processing_fee_line = $processing_fee_lines->next;
2210 is( $processing_fee_line->amount + 0,
2211 $processfee_amount, 'The right PF amount is generated' );
2212 is( $processing_fee_line->amountoutstanding + 0,
2213 $processfee_amount, 'The right PF amountoutstanding is generated' );
2215 my $lost_fee_lines = Koha::Account::Lines->search(
2216 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2217 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2218 my $lost_fee_line = $lost_fee_lines->next;
2219 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2220 is( $lost_fee_line->amountoutstanding + 0,
2221 $replacement_amount, 'The right L amountountstanding is generated' );
2223 my $account = $patron->account;
2224 is( $account->balance, $processfee_amount + $replacement_amount, 'Balance is PF + L' );
2226 # Partially pay fee
2227 my $payment_amount = 27;
2228 my $payment = $account->add_credit(
2229 { amount => $payment_amount,
2230 type => 'payment'
2234 $payment->apply( { debits => $lost_fee_lines->reset, offset_type => 'Payment' } );
2236 # Partially write off fee
2237 my $write_off_amount = 25;
2238 my $write_off = $account->add_credit(
2239 { amount => $write_off_amount,
2240 type => 'writeoff'
2243 $write_off->apply( { debits => $lost_fee_lines->reset, offset_type => 'Writeoff' } );
2245 is( $account->balance,
2246 $processfee_amount + $replacement_amount - $payment_amount - $write_off_amount,
2247 'Payment and write off applied'
2250 # Store the amountoutstanding value
2251 $lost_fee_line->discard_changes;
2252 my $outstanding = $lost_fee_line->amountoutstanding;
2254 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2255 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2257 is( $account->balance, $processfee_amount - $payment_amount, 'Balance is PF - payment (CR)' );
2259 $lost_fee_line->discard_changes;
2260 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2261 is( $lost_fee_line->accounttype,
2262 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2264 is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2265 is( $credit_return->amount + 0,
2266 ($payment_amount + $outstanding ) * -1,
2267 'The account line of type CR has an amount equal to the payment + outstanding'
2269 is( $credit_return->amountoutstanding + 0,
2270 $payment_amount * -1,
2271 'The account line of type CR has an amountoutstanding equal to the payment'
2274 is( $account->balance,
2275 $processfee_amount - $payment_amount,
2276 'The patron balance is the difference between the PF and the credit'
2280 subtest 'Partial payement, existing debits and AccountAutoReconcile' => sub {
2282 plan tests => 8;
2284 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2285 my $barcode = 'KD123456793';
2286 my $replacement_amount = 100;
2287 my $processfee_amount = 20;
2289 my $item_type = $builder->build_object(
2290 { class => 'Koha::ItemTypes',
2291 value => {
2292 notforloan => undef,
2293 rentalcharge => 0,
2294 defaultreplacecost => undef,
2295 processfee => 0,
2296 rentalcharge_daily => 0,
2300 my ( undef, undef, $item_id ) = AddItem(
2301 { homebranch => $library->branchcode,
2302 holdingbranch => $library->branchcode,
2303 barcode => $barcode,
2304 replacementprice => $replacement_amount,
2305 itype => $item_type->itemtype
2307 $biblio->biblionumber
2310 AddIssue( $patron->unblessed, $barcode );
2312 # Simulate item marked as lost
2313 ModItem( { itemlost => 1 }, $biblio->biblionumber, $item_id );
2314 LostItem( $item_id, 1 );
2316 my $lost_fee_lines = Koha::Account::Lines->search(
2317 { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'L' } );
2318 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2319 my $lost_fee_line = $lost_fee_lines->next;
2320 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2321 is( $lost_fee_line->amountoutstanding + 0,
2322 $replacement_amount, 'The right L amountountstanding is generated' );
2324 my $account = $patron->account;
2325 is( $account->balance, $replacement_amount, 'Balance is L' );
2327 # Partially pay fee
2328 my $payment_amount = 27;
2329 my $payment = $account->add_credit(
2330 { amount => $payment_amount,
2331 type => 'payment'
2334 $payment->apply({ debits => $lost_fee_lines->reset, offset_type => 'Payment' });
2336 is( $account->balance,
2337 $replacement_amount - $payment_amount,
2338 'Payment applied'
2341 my $manual_debit_amount = 80;
2342 $account->add_debit( { amount => $manual_debit_amount, type => 'fine' } );
2344 is( $account->balance, $manual_debit_amount + $replacement_amount - $payment_amount, 'Manual debit applied' );
2346 t::lib::Mocks::mock_preference( 'AccountAutoReconcile', 1 );
2348 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item_id, $patron->id );
2349 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2351 is( $account->balance, $manual_debit_amount - $payment_amount, 'Balance is PF - payment (CR)' );
2353 my $manual_debit = Koha::Account::Lines->search({ borrowernumber => $patron->id, accounttype => 'FU' })->next;
2354 is( $manual_debit->amountoutstanding + 0, $manual_debit_amount - $payment_amount, 'reconcile_balance was called' );
2358 subtest '_FixOverduesOnReturn' => sub {
2359 plan tests => 6;
2361 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
2363 my $branchcode = $library2->{branchcode};
2365 my $item = $builder->build_sample_item(
2367 biblionumber => $biblio->biblionumber,
2368 library => $branchcode,
2369 replacementprice => 99.00,
2370 itype => $itemtype,
2374 my $patron = $builder->build( { source => 'Borrower' } );
2376 ## Start with basic call, should just close out the open fine
2377 my $accountline = Koha::Account::Line->new(
2379 borrowernumber => $patron->{borrowernumber},
2380 accounttype => 'FU',
2381 itemnumber => $item->itemnumber,
2382 amount => 99.00,
2383 amountoutstanding => 99.00,
2384 lastincrement => 9.00,
2386 )->store();
2388 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber );
2390 $accountline->_result()->discard_changes();
2392 is( $accountline->amountoutstanding, '99.000000', 'Fine has the same amount outstanding as previously' );
2393 is( $accountline->accounttype, 'F', 'Open fine ( account type FU ) has been closed out ( account type F )');
2396 ## Run again, with exemptfine enabled
2397 $accountline->set(
2399 accounttype => 'FU',
2400 amountoutstanding => 99.00,
2402 )->store();
2404 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1 );
2406 $accountline->_result()->discard_changes();
2407 my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
2409 is( $accountline->amountoutstanding + 0, 0, 'Fine has been reduced to 0' );
2410 is( $accountline->accounttype, 'FFOR', 'Open fine ( account type FU ) has been set to fine forgiven ( account type FFOR )');
2411 is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
2412 is( $offset->amount, '-99.000000', "Amount of offset is correct" );
2415 subtest 'Set waiting flag' => sub {
2416 plan tests => 4;
2418 my $library_1 = $builder->build( { source => 'Branch' } );
2419 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2420 my $library_2 = $builder->build( { source => 'Branch' } );
2421 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2423 my $biblio = $builder->build( { source => 'Biblio' } );
2424 my $biblioitem = $builder->build( { source => 'Biblioitem', value => { biblionumber => $biblio->{biblionumber} } } );
2426 my $item = $builder->build(
2428 source => 'Item',
2429 value => {
2430 homebranch => $library_1->{branchcode},
2431 holdingbranch => $library_1->{branchcode},
2432 notforloan => 0,
2433 itemlost => 0,
2434 withdrawn => 0,
2435 biblionumber => $biblioitem->{biblionumber},
2440 set_userenv( $library_2 );
2441 my $reserve_id = AddReserve(
2442 $library_2->{branchcode}, $patron_2->{borrowernumber}, $biblioitem->{biblionumber},
2443 '', 1, undef, undef, '', undef, $item->{itemnumber},
2446 set_userenv( $library_1 );
2447 my $do_transfer = 1;
2448 my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
2449 ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2450 my $hold = Koha::Holds->find( $reserve_id );
2451 is( $hold->found, 'T', 'Hold is in transit' );
2453 my ( $status ) = CheckReserves($item->{itemnumber});
2454 is( $status, 'Reserved', 'Hold is not waiting yet');
2456 set_userenv( $library_2 );
2457 $do_transfer = 0;
2458 AddReturn( $item->{barcode}, $library_2->{branchcode} );
2459 ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2460 $hold = Koha::Holds->find( $reserve_id );
2461 is( $hold->found, 'W', 'Hold is waiting' );
2462 ( $status ) = CheckReserves($item->{itemnumber});
2463 is( $status, 'Waiting', 'Now the hold is waiting');
2466 subtest 'Cancel transfers on lost items' => sub {
2467 plan tests => 5;
2468 my $library_1 = $builder->build( { source => 'Branch' } );
2469 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2470 my $library_2 = $builder->build( { source => 'Branch' } );
2471 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2472 my $biblio = $builder->build( { source => 'Biblio' } );
2473 my $biblioitem = $builder->build( { source => 'Biblioitem', value => { biblionumber => $biblio->{biblionumber} } } );
2474 my $item = $builder->build(
2476 source => 'Item',
2477 value => {
2478 homebranch => $library_1->{branchcode},
2479 holdingbranch => $library_1->{branchcode},
2480 notforloan => 0,
2481 itemlost => 0,
2482 withdrawn => 0,
2483 biblionumber => $biblioitem->{biblionumber},
2488 set_userenv( $library_2 );
2489 my $reserve_id = AddReserve(
2490 $library_2->{branchcode}, $patron_2->{borrowernumber}, $biblioitem->{biblionumber}, '', 1, undef, undef, '', undef, $item->{itemnumber},
2493 #Return book and add transfer
2494 set_userenv( $library_1 );
2495 my $do_transfer = 1;
2496 my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
2497 ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2498 C4::Circulation::transferbook( $library_2->{branchcode}, $item->{barcode} );
2499 my $hold = Koha::Holds->find( $reserve_id );
2500 is( $hold->found, 'T', 'Hold is in transit' );
2502 #Check transfer exists and the items holding branch is the transfer destination branch before marking it as lost
2503 my ($datesent,$frombranch,$tobranch) = GetTransfers($item->{itemnumber});
2504 is( $tobranch, $library_2->{branchcode}, 'The transfer record exists in the branchtransfers table');
2505 my $itemcheck = Koha::Items->find($item->{itemnumber});
2506 is( $itemcheck->holdingbranch, $library_2->{branchcode}, 'Items holding branch is the transfers destination branch before it is marked as lost' );
2508 #Simulate item being marked as lost and confirm the transfer is deleted and the items holding branch is the transfers source branch
2509 ModItem( { itemlost => 1 }, $biblio->{biblionumber}, $item->{itemnumber} );
2510 LostItem( $item->{itemnumber}, 'test', 1 );
2511 ($datesent,$frombranch,$tobranch) = GetTransfers($item->{itemnumber});
2512 is( $tobranch, undef, 'The transfer on the lost item has been deleted as the LostItemCancelOutstandingTransfer is enabled');
2513 $itemcheck = Koha::Items->find($item->{itemnumber});
2514 is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Lost item with cancelled hold has holding branch equallying the transfers source branch' );
2517 subtest 'CanBookBeIssued | is_overdue' => sub {
2518 plan tests => 3;
2520 # Set a simple circ policy
2521 $dbh->do('DELETE FROM issuingrules');
2522 $dbh->do(
2523 q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
2524 issuelength, lengthunit,
2525 renewalsallowed, renewalperiod,
2526 norenewalbefore, auto_renew,
2527 fine, chargeperiod)
2528 VALUES (?, ?, ?, ?,
2529 ?, ?,
2530 ?, ?,
2531 ?, ?,
2532 ?, ?
2536 '*', '*', '*', 25,
2537 14, 'days',
2538 1, 7,
2539 undef, 0,
2540 .10, 1
2543 my $five_days_go = output_pref({ dt => dt_from_string->add( days => 5 ), dateonly => 1});
2544 my $ten_days_go = output_pref({ dt => dt_from_string->add( days => 10), dateonly => 1 });
2545 my $library = $builder->build( { source => 'Branch' } );
2546 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2548 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
2549 my $item = $builder->build(
2551 source => 'Item',
2552 value => {
2553 homebranch => $library->{branchcode},
2554 holdingbranch => $library->{branchcode},
2555 notforloan => 0,
2556 itemlost => 0,
2557 withdrawn => 0,
2558 biblionumber => $biblioitem->{biblionumber},
2563 my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $five_days_go ); # date due was 10d ago
2564 my $actualissue = Koha::Checkouts->find( { itemnumber => $item->{itemnumber} } );
2565 is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
2566 my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->{barcode},$ten_days_go, undef, undef, undef);
2567 is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
2568 is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
2571 subtest 'ItemsDeniedRenewal preference' => sub {
2572 plan tests => 18;
2574 C4::Context->set_preference('ItemsDeniedRenewal','');
2576 my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
2577 $dbh->do(
2579 INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, issuelength, lengthunit, renewalsallowed, renewalperiod,
2580 norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
2583 '*', $idr_lib->branchcode, '*', 25,
2584 14, 'days',
2585 10, 7,
2586 undef, 0,
2587 .10, 1
2590 my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
2591 homebranch => $idr_lib->branchcode,
2592 withdrawn => 1,
2593 itype => 'HIDE',
2594 location => 'PROC',
2595 itemcallnumber => undef,
2596 itemnotes => "",
2599 my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
2600 homebranch => $idr_lib->branchcode,
2601 withdrawn => 0,
2602 itype => 'NOHIDE',
2603 location => 'NOPROC'
2607 my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
2608 branchcode => $idr_lib->branchcode,
2611 my $future = dt_from_string->add( days => 1 );
2612 my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
2613 returndate => undef,
2614 renewals => 0,
2615 auto_renew => 0,
2616 borrowernumber => $idr_borrower->borrowernumber,
2617 itemnumber => $deny_book->itemnumber,
2618 onsite_checkout => 0,
2619 date_due => $future,
2622 my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
2623 returndate => undef,
2624 renewals => 0,
2625 auto_renew => 0,
2626 borrowernumber => $idr_borrower->borrowernumber,
2627 itemnumber => $allow_book->itemnumber,
2628 onsite_checkout => 0,
2629 date_due => $future,
2633 my $idr_rules;
2635 my ( $idr_mayrenew, $idr_error ) =
2636 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2637 is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
2638 is( $idr_error, undef, 'Renewal allowed when no rules' );
2640 $idr_rules="withdrawn: [1]";
2642 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2643 ( $idr_mayrenew, $idr_error ) =
2644 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2645 is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
2646 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
2647 ( $idr_mayrenew, $idr_error ) =
2648 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2649 is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
2650 is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
2652 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
2654 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2655 ( $idr_mayrenew, $idr_error ) =
2656 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2657 is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
2658 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
2659 ( $idr_mayrenew, $idr_error ) =
2660 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2661 is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
2662 is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
2664 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
2666 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2667 ( $idr_mayrenew, $idr_error ) =
2668 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2669 is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
2670 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
2671 ( $idr_mayrenew, $idr_error ) =
2672 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2673 is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
2674 is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
2676 $idr_rules="itemcallnumber: [NULL]";
2677 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2678 ( $idr_mayrenew, $idr_error ) =
2679 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2680 is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
2681 $idr_rules="itemcallnumber: ['']";
2682 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2683 ( $idr_mayrenew, $idr_error ) =
2684 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2685 is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
2687 $idr_rules="itemnotes: [NULL]";
2688 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2689 ( $idr_mayrenew, $idr_error ) =
2690 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2691 is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
2692 $idr_rules="itemnotes: ['']";
2693 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2694 ( $idr_mayrenew, $idr_error ) =
2695 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2696 is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
2699 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
2700 plan tests => 2;
2702 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
2703 my $library = $builder->build( { source => 'Branch' } );
2704 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
2706 my $itemtype = $builder->build(
2708 source => 'Itemtype',
2709 value => { notforloan => undef, }
2713 my $biblioitem = $builder->build( { source => 'Biblioitem', value => { itemtype => $itemtype->{itemtype} } } );
2714 my $item = $builder->build_object(
2716 class => 'Koha::Items',
2717 value => {
2718 homebranch => $library->{branchcode},
2719 holdingbranch => $library->{branchcode},
2720 notforloan => 0,
2721 itemlost => 0,
2722 withdrawn => 0,
2723 biblionumber => $biblioitem->{biblionumber},
2724 biblioitemnumber => $biblioitem->{biblioitemnumber},
2727 )->store;
2729 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2730 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2731 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2734 subtest 'CanBookBeIssued | notforloan' => sub {
2735 plan tests => 2;
2737 t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
2739 my $library = $builder->build( { source => 'Branch' } );
2740 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
2742 my $itemtype = $builder->build(
2744 source => 'Itemtype',
2745 value => { notforloan => undef, }
2749 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
2750 my $item = $builder->build_object(
2752 class => 'Koha::Items',
2753 value => {
2754 homebranch => $library->{branchcode},
2755 holdingbranch => $library->{branchcode},
2756 notforloan => 0,
2757 itemlost => 0,
2758 withdrawn => 0,
2759 itype => $itemtype->{itemtype},
2760 biblionumber => $biblioitem->{biblionumber},
2761 biblioitemnumber => $biblioitem->{biblioitemnumber},
2764 )->store;
2766 my ( $issuingimpossible, $needsconfirmation );
2769 subtest 'item-level_itypes = 1' => sub {
2770 plan tests => 6;
2772 t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
2773 # Is for loan at item type and item level
2774 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2775 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2776 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2778 # not for loan at item type level
2779 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
2780 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2781 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2782 is_deeply(
2783 $issuingimpossible,
2784 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
2785 'Item can not be issued, not for loan at item type level'
2788 # not for loan at item level
2789 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
2790 $item->notforloan( 1 )->store;
2791 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2792 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2793 is_deeply(
2794 $issuingimpossible,
2795 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
2796 'Item can not be issued, not for loan at item type level'
2800 subtest 'item-level_itypes = 0' => sub {
2801 plan tests => 6;
2803 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
2805 # We set another itemtype for biblioitem
2806 my $itemtype = $builder->build(
2808 source => 'Itemtype',
2809 value => { notforloan => undef, }
2813 # for loan at item type and item level
2814 $item->notforloan(0)->store;
2815 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
2816 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2817 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2818 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2820 # not for loan at item type level
2821 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
2822 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2823 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2824 is_deeply(
2825 $issuingimpossible,
2826 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
2827 'Item can not be issued, not for loan at item type level'
2830 # not for loan at item level
2831 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
2832 $item->notforloan( 1 )->store;
2833 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2834 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2835 is_deeply(
2836 $issuingimpossible,
2837 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
2838 'Item can not be issued, not for loan at item type level'
2842 # TODO test with AllowNotForLoanOverride = 1
2845 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
2846 plan tests => 1;
2848 t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
2849 my $item = $builder->build_object({ class => 'Koha::Items', value => { onloan => '2018-01-01' }});
2850 AddReturn( $item->barcode, $item->homebranch );
2851 $item->discard_changes; # refresh
2852 is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
2855 $schema->storage->txn_rollback;
2856 C4::Context->clear_syspref_cache();
2857 $cache->clear_from_cache('single_holidays');
2859 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
2861 plan tests => 13;
2863 $schema->storage->txn_begin;
2865 t::lib::Mocks::mock_preference('item-level_itypes', 1);
2867 my $issuing_charges = 15;
2868 my $title = 'A title';
2869 my $author = 'Author, An';
2870 my $barcode = 'WHATARETHEODDS';
2872 my $circ = Test::MockModule->new('C4::Circulation');
2873 $circ->mock(
2874 'GetIssuingCharges',
2875 sub {
2876 return $issuing_charges;
2880 my $library = $builder->build_object({ class => 'Koha::Libraries' });
2881 my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
2882 my $patron = $builder->build_object({
2883 class => 'Koha::Patrons',
2884 value => { branchcode => $library->id }
2887 my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
2888 my ( undef, undef, $item_id ) = AddItem(
2890 homebranch => $library->id,
2891 holdingbranch => $library->id,
2892 barcode => $barcode,
2893 replacementprice => 23.00,
2894 itype => $itemtype->id
2896 $biblio->biblionumber
2898 my $item = Koha::Items->find( $item_id );
2900 my $context = Test::MockModule->new('C4::Context');
2901 $context->mock( userenv => { branch => $library->id } );
2903 # Check the item out
2904 AddIssue( $patron->unblessed, $item->barcode );
2905 t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
2906 my $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
2907 my %params_renewal = (
2908 timestamp => { -like => $date . "%" },
2909 module => "CIRCULATION",
2910 action => "RENEWAL",
2912 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
2913 AddRenewal( $patron->id, $item->id, $library->id );
2914 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
2915 is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
2917 my $checkouts = $patron->checkouts;
2918 # The following will fail if run on 00:00:00
2919 unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
2921 t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
2922 $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
2923 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
2924 AddRenewal( $patron->id, $item->id, $library->id );
2925 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
2926 is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
2928 my $lines = Koha::Account::Lines->search({
2929 borrowernumber => $patron->id,
2930 itemnumber => $item->id
2933 is( $lines->count, 3 );
2935 my $line = $lines->next;
2936 is( $line->accounttype, 'Rent', 'The issuing charge generates an accountline' );
2937 is( $line->branchcode, $library->id, 'AddIssuingCharge correctly sets branchcode' );
2938 is( $line->description, 'Rental', 'AddIssuingCharge set a hardcoded description for the accountline' );
2940 $line = $lines->next;
2941 is( $line->accounttype, 'Rent', 'Fine on renewed item is closed out properly' );
2942 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
2943 is( $line->description, "Renewal of Rental Item $title $barcode", 'AddRenewal set a hardcoded description for the accountline' );
2945 $line = $lines->next;
2946 is( $line->accounttype, 'Rent', 'Fine on renewed item is closed out properly' );
2947 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
2948 is( $line->description, "Renewal of Rental Item $title $barcode", 'AddRenewal set a hardcoded description for the accountline' );
2950 $schema->storage->txn_rollback;
2953 subtest 'ProcessOfflinePayment() tests' => sub {
2955 plan tests => 4;
2957 $schema->storage->txn_begin;
2959 my $amount = 123;
2961 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
2962 my $library = $builder->build_object({ class => 'Koha::Libraries' });
2963 my $result = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
2965 is( $result, 'Success.', 'The right string is returned' );
2967 my $lines = $patron->account->lines;
2968 is( $lines->count, 1, 'line created correctly');
2970 my $line = $lines->next;
2971 is( $line->amount+0, $amount * -1, 'amount picked from params' );
2972 is( $line->branchcode, $library->id, 'branchcode set correctly' );
2974 $schema->storage->txn_rollback;
2979 sub set_userenv {
2980 my ( $library ) = @_;
2981 t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
2984 sub str {
2985 my ( $error, $question, $alert ) = @_;
2986 my $s;
2987 $s = %$error ? ' (error: ' . join( ' ', keys %$error ) . ')' : '';
2988 $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
2989 $s .= %$alert ? ' (alert: ' . join( ' ', keys %$alert ) . ')' : '';
2990 return $s;
2993 sub test_debarment_on_checkout {
2994 my ($params) = @_;
2995 my $item = $params->{item};
2996 my $library = $params->{library};
2997 my $patron = $params->{patron};
2998 my $due_date = $params->{due_date} || dt_from_string;
2999 my $return_date = $params->{return_date} || dt_from_string;
3000 my $expected_expiration_date = $params->{expiration_date};
3002 $expected_expiration_date = output_pref(
3004 dt => $expected_expiration_date,
3005 dateformat => 'sql',
3006 dateonly => 1,
3009 my @caller = caller;
3010 my $line_number = $caller[2];
3011 AddIssue( $patron, $item->{barcode}, $due_date );
3013 my ( undef, $message ) = AddReturn( $item->{barcode}, $library->{branchcode}, undef, $return_date );
3014 is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' )
3015 or diag('AddReturn returned message ' . Dumper $message );
3016 my $debarments = Koha::Patron::Debarments::GetDebarments(
3017 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
3018 is( scalar(@$debarments), 1, 'Test at line ' . $line_number );
3020 is( $debarments->[0]->{expiration},
3021 $expected_expiration_date, 'Test at line ' . $line_number );
3022 Koha::Patron::Debarments::DelUniqueDebarment(
3023 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
3026 subtest 'Incremented fee tests' => sub {
3027 plan tests => 11;
3029 t::lib::Mocks::mock_preference('item-level_itypes', 1);
3031 my $library = $builder->build_object( { class => 'Koha::Libraries' } )->store;
3033 my $module = new Test::MockModule('C4::Context');
3034 $module->mock('userenv', sub { { branch => $library->id } });
3036 my $patron = $builder->build_object(
3038 class => 'Koha::Patrons',
3039 value => { categorycode => $patron_category->{categorycode} }
3041 )->store;
3043 my $itemtype = $builder->build_object(
3045 class => 'Koha::ItemTypes',
3046 value => {
3047 notforloan => undef,
3048 rentalcharge => 0,
3049 rentalcharge_daily => 1.000000
3052 )->store;
3054 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
3055 my $item = $builder->build_object(
3057 class => 'Koha::Items',
3058 value => {
3059 homebranch => $library->id,
3060 holdingbranch => $library->id,
3061 notforloan => 0,
3062 itemlost => 0,
3063 withdrawn => 0,
3064 itype => $itemtype->id,
3065 biblionumber => $biblioitem->{biblionumber},
3066 biblioitemnumber => $biblioitem->{biblioitemnumber},
3069 )->store;
3071 is( $itemtype->rentalcharge_daily, '1.000000', 'Daily rental charge stored and retreived correctly' );
3072 is( $item->effective_itemtype, $itemtype->id, "Itemtype set correctly for item");
3074 my $dt_from = dt_from_string();
3075 my $dt_to = dt_from_string()->add( days => 7 );
3076 my $dt_to_renew = dt_from_string()->add( days => 13 );
3078 t::lib::Mocks::mock_preference('finesCalendar', 'ignoreCalendar');
3079 my $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3080 my $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3081 is( $accountline->amount, '7.000000', "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar" );
3082 $accountline->delete();
3083 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3084 $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3085 is( $accountline->amount, '6.000000', "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar, for renewal" );
3086 $accountline->delete();
3087 $issue->delete();
3089 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
3090 $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3091 $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3092 is( $accountline->amount, '7.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed" );
3093 $accountline->delete();
3094 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3095 $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3096 is( $accountline->amount, '6.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed, for renewal" );
3097 $accountline->delete();
3098 $issue->delete();
3100 my $calendar = C4::Calendar->new( branchcode => $library->id );
3101 $calendar->insert_week_day_holiday(
3102 weekday => 3,
3103 title => 'Test holiday',
3104 description => 'Test holiday'
3106 $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3107 $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3108 is( $accountline->amount, '6.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed Wednesdays" );
3109 $accountline->delete();
3110 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3111 $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3112 is( $accountline->amount, '5.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed Wednesdays, for renewal" );
3113 $accountline->delete();
3114 $issue->delete();
3116 $itemtype->rentalcharge('2.000000')->store;
3117 is( $itemtype->rentalcharge, '2.000000', 'Rental charge updated and retreived correctly' );
3118 $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from);
3119 my $accountlines = Koha::Account::Lines->search({ itemnumber => $item->id });
3120 is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly");
3121 $accountlines->delete();
3122 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3123 $accountlines = Koha::Account::Lines->search({ itemnumber => $item->id });
3124 is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly, for renewal");
3125 $accountlines->delete();
3126 $issue->delete();
3129 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
3130 plan tests => 2;
3132 t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
3133 t::lib::Mocks::mock_preference('item-level_itypes', 1);
3135 my $library =
3136 $builder->build_object( { class => 'Koha::Libraries' } )->store;
3137 my $patron = $builder->build_object(
3139 class => 'Koha::Patrons',
3140 value => { categorycode => $patron_category->{categorycode} }
3142 )->store;
3144 my $itemtype = $builder->build_object(
3146 class => 'Koha::ItemTypes',
3147 value => {
3148 notforloan => 0,
3149 rentalcharge => 0,
3150 rentalcharge_daily => 0
3155 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
3156 my $item = $builder->build_object(
3158 class => 'Koha::Items',
3159 value => {
3160 homebranch => $library->id,
3161 holdingbranch => $library->id,
3162 notforloan => 0,
3163 itemlost => 0,
3164 withdrawn => 0,
3165 itype => $itemtype->id,
3166 biblionumber => $biblioitem->{biblionumber},
3167 biblioitemnumber => $biblioitem->{biblioitemnumber},
3170 )->store;
3172 my ( $issuingimpossible, $needsconfirmation );
3173 my $dt_from = dt_from_string();
3174 my $dt_due = dt_from_string()->add( days => 3 );
3176 $itemtype->rentalcharge('1.000000')->store;
3177 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3178 is_deeply( $needsconfirmation, { RENTALCHARGE => '1' }, 'Item needs rentalcharge confirmation to be issued' );
3179 $itemtype->rentalcharge('0')->store;
3180 $itemtype->rentalcharge_daily('1.000000')->store;
3181 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3182 is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
3183 $itemtype->rentalcharge_daily('0')->store;