Bug 15774: Fix additional fields filters
[koha.git] / t / db_dependent / Circulation.t
blob3d52a1ffa449970f5ba948ea237dfbb1d1e5776a
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;
49 my $schema = Koha::Database->schema;
50 $schema->storage->txn_begin;
51 my $builder = t::lib::TestBuilder->new;
52 my $dbh = C4::Context->dbh;
54 # Start transaction
55 $dbh->{RaiseError} = 1;
57 my $cache = Koha::Caches->get_instance();
58 $dbh->do(q|DELETE FROM special_holidays|);
59 $dbh->do(q|DELETE FROM repeatable_holidays|);
60 $cache->clear_from_cache('single_holidays');
62 # Start with a clean slate
63 $dbh->do('DELETE FROM issues');
64 $dbh->do('DELETE FROM borrowers');
66 my $library = $builder->build({
67 source => 'Branch',
68 });
69 my $library2 = $builder->build({
70 source => 'Branch',
71 });
72 my $itemtype = $builder->build(
74 source => 'Itemtype',
75 value => {
76 notforloan => undef,
77 rentalcharge => 0,
78 rentalcharge_daily => 0,
79 defaultreplacecost => undef,
80 processfee => undef
83 )->{itemtype};
84 my $patron_category = $builder->build(
86 source => 'Category',
87 value => {
88 category_type => 'P',
89 enrolmentfee => 0,
90 BlockExpiredPatronOpacActions => -1, # Pick the pref value
95 my $CircControl = C4::Context->preference('CircControl');
96 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
98 my $item = {
99 homebranch => $library2->{branchcode},
100 holdingbranch => $library2->{branchcode}
103 my $borrower = {
104 branchcode => $library2->{branchcode}
107 # No userenv, PickupLibrary
108 t::lib::Mocks::mock_preference('IndependentBranches', '0');
109 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
111 C4::Context->preference('CircControl'),
112 'PickupLibrary',
113 'CircControl changed to PickupLibrary'
116 C4::Circulation::_GetCircControlBranch($item, $borrower),
117 $item->{$HomeOrHoldingBranch},
118 '_GetCircControlBranch returned item branch (no userenv defined)'
121 # No userenv, PatronLibrary
122 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
124 C4::Context->preference('CircControl'),
125 'PatronLibrary',
126 'CircControl changed to PatronLibrary'
129 C4::Circulation::_GetCircControlBranch($item, $borrower),
130 $borrower->{branchcode},
131 '_GetCircControlBranch returned borrower branch'
134 # No userenv, ItemHomeLibrary
135 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
137 C4::Context->preference('CircControl'),
138 'ItemHomeLibrary',
139 'CircControl changed to ItemHomeLibrary'
142 $item->{$HomeOrHoldingBranch},
143 C4::Circulation::_GetCircControlBranch($item, $borrower),
144 '_GetCircControlBranch returned item branch'
147 # Now, set a userenv
148 t::lib::Mocks::mock_userenv({ branchcode => $library2->{branchcode} });
149 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
151 # Userenv set, PickupLibrary
152 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
154 C4::Context->preference('CircControl'),
155 'PickupLibrary',
156 'CircControl changed to PickupLibrary'
159 C4::Circulation::_GetCircControlBranch($item, $borrower),
160 $library2->{branchcode},
161 '_GetCircControlBranch returned current branch'
164 # Userenv set, PatronLibrary
165 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
167 C4::Context->preference('CircControl'),
168 'PatronLibrary',
169 'CircControl changed to PatronLibrary'
172 C4::Circulation::_GetCircControlBranch($item, $borrower),
173 $borrower->{branchcode},
174 '_GetCircControlBranch returned borrower branch'
177 # Userenv set, ItemHomeLibrary
178 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
180 C4::Context->preference('CircControl'),
181 'ItemHomeLibrary',
182 'CircControl changed to ItemHomeLibrary'
185 C4::Circulation::_GetCircControlBranch($item, $borrower),
186 $item->{$HomeOrHoldingBranch},
187 '_GetCircControlBranch returned item branch'
190 # Reset initial configuration
191 t::lib::Mocks::mock_preference('CircControl', $CircControl);
193 C4::Context->preference('CircControl'),
194 $CircControl,
195 'CircControl reset to its initial value'
198 # Set a simple circ policy
199 $dbh->do('DELETE FROM issuingrules');
200 Koha::CirculationRules->search()->delete();
201 $dbh->do(
202 q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
203 issuelength, lengthunit,
204 renewalsallowed, renewalperiod,
205 norenewalbefore, auto_renew,
206 fine, chargeperiod)
207 VALUES (?, ?, ?, ?,
208 ?, ?,
209 ?, ?,
210 ?, ?,
211 ?, ?
215 '*', '*', '*', 25,
216 14, 'days',
217 1, 7,
218 undef, 0,
219 .10, 1
222 my ( $reused_itemnumber_1, $reused_itemnumber_2 );
224 # CanBookBeRenewed tests
225 C4::Context->set_preference('ItemsDeniedRenewal','');
226 # Generate test biblio
227 my $biblio = $builder->build_sample_biblio();
229 my $branch = $library2->{branchcode};
231 my $item_1 = $builder->build_sample_item(
233 biblionumber => $biblio->biblionumber,
234 library => $branch,
235 replacementprice => 12.00,
236 itype => $itemtype
239 $reused_itemnumber_1 = $item_1->itemnumber;
241 my $item_2 = $builder->build_sample_item(
243 biblionumber => $biblio->biblionumber,
244 library => $branch,
245 replacementprice => 23.00,
246 itype => $itemtype
249 $reused_itemnumber_2 = $item_2->itemnumber;
251 my $item_3 = $builder->build_sample_item(
253 biblionumber => $biblio->biblionumber,
254 library => $branch,
255 replacementprice => 23.00,
256 itype => $itemtype
260 # Create borrowers
261 my %renewing_borrower_data = (
262 firstname => 'John',
263 surname => 'Renewal',
264 categorycode => $patron_category->{categorycode},
265 branchcode => $branch,
268 my %reserving_borrower_data = (
269 firstname => 'Katrin',
270 surname => 'Reservation',
271 categorycode => $patron_category->{categorycode},
272 branchcode => $branch,
275 my %hold_waiting_borrower_data = (
276 firstname => 'Kyle',
277 surname => 'Reservation',
278 categorycode => $patron_category->{categorycode},
279 branchcode => $branch,
282 my %restricted_borrower_data = (
283 firstname => 'Alice',
284 surname => 'Reservation',
285 categorycode => $patron_category->{categorycode},
286 debarred => '3228-01-01',
287 branchcode => $branch,
290 my %expired_borrower_data = (
291 firstname => 'Ça',
292 surname => 'Glisse',
293 categorycode => $patron_category->{categorycode},
294 branchcode => $branch,
295 dateexpiry => dt_from_string->subtract( months => 1 ),
298 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
299 my $reserving_borrowernumber = Koha::Patron->new(\%reserving_borrower_data)->store->borrowernumber;
300 my $hold_waiting_borrowernumber = Koha::Patron->new(\%hold_waiting_borrower_data)->store->borrowernumber;
301 my $restricted_borrowernumber = Koha::Patron->new(\%restricted_borrower_data)->store->borrowernumber;
302 my $expired_borrowernumber = Koha::Patron->new(\%expired_borrower_data)->store->borrowernumber;
304 my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
305 my $restricted_borrower = Koha::Patrons->find( $restricted_borrowernumber )->unblessed;
306 my $expired_borrower = Koha::Patrons->find( $expired_borrowernumber )->unblessed;
308 my $bibitems = '';
309 my $priority = '1';
310 my $resdate = undef;
311 my $expdate = undef;
312 my $notes = '';
313 my $checkitem = undef;
314 my $found = undef;
316 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
317 my $datedue = dt_from_string( $issue->date_due() );
318 is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
320 my $issue2 = AddIssue( $renewing_borrower, $item_2->barcode);
321 $datedue = dt_from_string( $issue->date_due() );
322 is (defined $issue2, 1, "Item 2 checked out, due date: " . $issue2->date_due());
325 my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $item_1->itemnumber } )->borrowernumber;
326 is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
328 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
329 is( $renewokay, 1, 'Can renew, no holds for this title or item');
332 # Biblio-level hold, renewal test
333 AddReserve(
334 $branch, $reserving_borrowernumber, $biblio->biblionumber,
335 $bibitems, $priority, $resdate, $expdate, $notes,
336 'a title', $checkitem, $found
339 # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
340 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
341 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
342 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
343 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
344 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
345 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
347 # Now let's add an item level hold, we should no longer be able to renew the item
348 my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
350 borrowernumber => $hold_waiting_borrowernumber,
351 biblionumber => $biblio->biblionumber,
352 itemnumber => $item_1->itemnumber,
353 branchcode => $branch,
354 priority => 3,
357 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
358 is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
359 $hold->delete();
361 # 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
362 # be able to renew these items
363 $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
365 borrowernumber => $hold_waiting_borrowernumber,
366 biblionumber => $biblio->biblionumber,
367 itemnumber => $item_3->itemnumber,
368 branchcode => $branch,
369 priority => 0,
370 found => 'W'
373 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
374 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
375 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
376 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
377 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
379 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
380 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
381 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
383 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
384 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
385 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
387 my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
388 my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber )->unblessed;
389 AddIssue($reserving_borrower, $item_3->barcode);
390 my $reserve = $dbh->selectrow_hashref(
391 'SELECT * FROM old_reserves WHERE reserve_id = ?',
392 { Slice => {} },
393 $reserveid
395 is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
397 # Item-level hold, renewal test
398 AddReserve(
399 $branch, $reserving_borrowernumber, $biblio->biblionumber,
400 $bibitems, $priority, $resdate, $expdate, $notes,
401 'a title', $item_1->itemnumber, $found
404 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
405 is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
406 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
408 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber, 1);
409 is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
411 # Items can't fill hold for reasons
412 ModItem({ notforloan => 1 }, $biblio->biblionumber, $item_1->itemnumber);
413 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
414 is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
415 ModItem({ notforloan => 0, itype => $itemtype }, $biblio->biblionumber, $item_1->itemnumber);
417 # FIXME: Add more for itemtype not for loan etc.
419 # Restricted users cannot renew when RestrictionBlockRenewing is enabled
420 my $item_5 = $builder->build_sample_item(
422 biblionumber => $biblio->biblionumber,
423 library => $branch,
424 replacementprice => 23.00,
425 itype => $itemtype,
428 my $datedue5 = AddIssue($restricted_borrower, $item_5->barcode);
429 is (defined $datedue5, 1, "Item with date due checked out, due date: $datedue5");
431 t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
432 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
433 is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
434 ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrowernumber, $item_5->itemnumber);
435 is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
437 # Users cannot renew an overdue item
438 my $item_6 = $builder->build_sample_item(
440 biblionumber => $biblio->biblionumber,
441 library => $branch,
442 replacementprice => 23.00,
443 itype => $itemtype,
447 my $item_7 = $builder->build_sample_item(
449 biblionumber => $biblio->biblionumber,
450 library => $branch,
451 replacementprice => 23.00,
452 itype => $itemtype,
456 my $datedue6 = AddIssue( $renewing_borrower, $item_6->barcode);
457 is (defined $datedue6, 1, "Item 2 checked out, due date: ".$datedue6->date_due);
459 my $now = dt_from_string();
460 my $five_weeks = DateTime::Duration->new(weeks => 5);
461 my $five_weeks_ago = $now - $five_weeks;
462 t::lib::Mocks::mock_preference('finesMode', 'production');
464 my $passeddatedue1 = AddIssue($renewing_borrower, $item_7->barcode, $five_weeks_ago);
465 is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: " . $passeddatedue1->date_due);
467 my ( $fine ) = CalcFine( $item_7->unblessed, $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
468 C4::Overdues::UpdateFine(
470 issue_id => $passeddatedue1->id(),
471 itemnumber => $item_7->itemnumber,
472 borrowernumber => $renewing_borrower->{borrowernumber},
473 amount => $fine,
474 due => Koha::DateUtils::output_pref($five_weeks_ago)
478 t::lib::Mocks::mock_preference('RenewalLog', 0);
479 my $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
480 my $old_log_size = scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
481 AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
482 my $new_log_size = scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
483 is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
485 t::lib::Mocks::mock_preference('RenewalLog', 1);
486 $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
487 $old_log_size = scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
488 AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
489 $new_log_size = scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
490 is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
492 my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
493 is( $fines->count, 2 );
494 is( $fines->next->accounttype, 'F', 'Fine on renewed item is closed out properly' );
495 is( $fines->next->accounttype, 'F', 'Fine on renewed item is closed out properly' );
496 $fines->delete();
499 my $old_issue_log_size = scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["ISSUE"]) } );
500 my $old_renew_log_size = scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
501 AddIssue( $renewing_borrower,$item_7->barcode,Koha::DateUtils::output_pref({str=>$datedue6->date_due, dateformat =>'iso'}),0,$date, 0, undef );
502 $new_log_size = scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
503 is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
504 $new_log_size = scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["ISSUE"]) } );
505 is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
507 $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
508 $fines->delete();
510 t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
511 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
512 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
513 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
514 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
517 $hold = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next;
518 $hold->cancel;
520 # Bug 14101
521 # Test automatic renewal before value for "norenewalbefore" in policy is set
522 # In this case automatic renewal is not permitted prior to due date
523 my $item_4 = $builder->build_sample_item(
525 biblionumber => $biblio->biblionumber,
526 library => $branch,
527 replacementprice => 16.00,
528 itype => $itemtype,
532 $issue = AddIssue( $renewing_borrower, $item_4->barcode, undef, undef, undef, undef, { auto_renew => 1 } );
533 ( $renewokay, $error ) =
534 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
535 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
536 is( $error, 'auto_too_soon',
537 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
539 # Bug 7413
540 # Test premature manual renewal
541 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7');
543 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
544 is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
545 is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
547 # Bug 14395
548 # Test 'exact time' setting for syspref NoRenewalBeforePrecision
549 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
551 GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
552 $datedue->clone->add( days => -7 ),
553 'Bug 14395: Renewals permitted 7 days before due date, as expected'
556 # Bug 14395
557 # Test 'date' setting for syspref NoRenewalBeforePrecision
558 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
560 GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
561 $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
562 'Bug 14395: Renewals permitted 7 days before due date, as expected'
565 # Bug 14101
566 # Test premature automatic renewal
567 ( $renewokay, $error ) =
568 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
569 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
570 is( $error, 'auto_too_soon',
571 'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
574 # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
575 # and test automatic renewal again
576 $dbh->do('UPDATE issuingrules SET norenewalbefore = 0');
577 ( $renewokay, $error ) =
578 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
579 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
580 is( $error, 'auto_too_soon',
581 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
584 # Change policy so that loans can be renewed 99 days prior to the due date
585 # and test automatic renewal again
586 $dbh->do('UPDATE issuingrules SET norenewalbefore = 99');
587 ( $renewokay, $error ) =
588 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
589 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
590 is( $error, 'auto_renew',
591 'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
594 subtest "too_late_renewal / no_auto_renewal_after" => sub {
595 plan tests => 14;
596 my $item_to_auto_renew = $builder->build(
597 { source => 'Item',
598 value => {
599 biblionumber => $biblio->biblionumber,
600 homebranch => $branch,
601 holdingbranch => $branch,
606 my $ten_days_before = dt_from_string->add( days => -10 );
607 my $ten_days_ahead = dt_from_string->add( days => 10 );
608 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
610 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 9');
611 ( $renewokay, $error ) =
612 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
613 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
614 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
616 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 10');
617 ( $renewokay, $error ) =
618 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
619 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
620 is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
622 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 11');
623 ( $renewokay, $error ) =
624 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
625 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
626 is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
628 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
629 ( $renewokay, $error ) =
630 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
631 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
632 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
634 $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 ) );
635 ( $renewokay, $error ) =
636 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
637 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
638 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
640 $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 ) );
641 ( $renewokay, $error ) =
642 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
643 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
644 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
646 $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 ) );
647 ( $renewokay, $error ) =
648 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
649 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
650 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
653 subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew" => sub {
654 plan tests => 6;
655 my $item_to_auto_renew = $builder->build({
656 source => 'Item',
657 value => {
658 biblionumber => $biblio->biblionumber,
659 homebranch => $branch,
660 holdingbranch => $branch,
664 my $ten_days_before = dt_from_string->add( days => -10 );
665 my $ten_days_ahead = dt_from_string->add( days => 10 );
666 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
668 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
669 C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
670 C4::Context->set_preference('OPACFineNoRenewals','10');
671 my $fines_amount = 5;
672 C4::Accounts::manualinvoice( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber}, "Some fines", 'F', $fines_amount );
673 ( $renewokay, $error ) =
674 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
675 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
676 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
678 C4::Accounts::manualinvoice( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber}, "Some fines", 'F', $fines_amount );
679 ( $renewokay, $error ) =
680 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
681 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
682 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
684 C4::Accounts::manualinvoice( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber}, "Some fines", 'F', $fines_amount );
685 ( $renewokay, $error ) =
686 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
687 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
688 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
690 $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
693 subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
694 plan tests => 6;
695 my $item_to_auto_renew = $builder->build({
696 source => 'Item',
697 value => {
698 biblionumber => $biblio->biblionumber,
699 homebranch => $branch,
700 holdingbranch => $branch,
704 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
706 my $ten_days_before = dt_from_string->add( days => -10 );
707 my $ten_days_ahead = dt_from_string->add( days => 10 );
709 # Patron is expired and BlockExpiredPatronOpacActions=0
710 # => auto renew is allowed
711 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
712 my $patron = $expired_borrower;
713 my $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
714 ( $renewokay, $error ) =
715 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
716 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
717 is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
718 Koha::Checkouts->find( $checkout->issue_id )->delete;
721 # Patron is expired and BlockExpiredPatronOpacActions=1
722 # => auto renew is not allowed
723 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
724 $patron = $expired_borrower;
725 $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
726 ( $renewokay, $error ) =
727 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
728 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
729 is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
730 Koha::Checkouts->find( $checkout->issue_id )->delete;
733 # Patron is not expired and BlockExpiredPatronOpacActions=1
734 # => auto renew is allowed
735 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
736 $patron = $renewing_borrower;
737 $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
738 ( $renewokay, $error ) =
739 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
740 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
741 is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
742 Koha::Checkouts->find( $checkout->issue_id )->delete;
745 subtest "GetLatestAutoRenewDate" => sub {
746 plan tests => 5;
747 my $item_to_auto_renew = $builder->build(
748 { source => 'Item',
749 value => {
750 biblionumber => $biblio->biblionumber,
751 homebranch => $branch,
752 holdingbranch => $branch,
757 my $ten_days_before = dt_from_string->add( days => -10 );
758 my $ten_days_ahead = dt_from_string->add( days => 10 );
759 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
760 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = NULL, no_auto_renewal_after_hard_limit = NULL');
761 my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
762 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' );
763 my $five_days_before = dt_from_string->add( days => -5 );
764 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 5, no_auto_renewal_after_hard_limit = NULL');
765 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
766 is( $latest_auto_renew_date->truncate( to => 'minute' ),
767 $five_days_before->truncate( to => 'minute' ),
768 'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
770 my $five_days_ahead = dt_from_string->add( days => 5 );
771 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 15, no_auto_renewal_after_hard_limit = NULL');
772 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
773 is( $latest_auto_renew_date->truncate( to => 'minute' ),
774 $five_days_ahead->truncate( to => 'minute' ),
775 'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
777 my $two_days_ahead = dt_from_string->add( days => 2 );
778 $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 ) );
779 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
780 is( $latest_auto_renew_date->truncate( to => 'day' ),
781 $two_days_ahead->truncate( to => 'day' ),
782 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
784 $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 ) );
785 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
786 is( $latest_auto_renew_date->truncate( to => 'day' ),
787 $two_days_ahead->truncate( to => 'day' ),
788 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
793 # Too many renewals
795 # set policy to forbid renewals
796 $dbh->do('UPDATE issuingrules SET norenewalbefore = NULL, renewalsallowed = 0');
798 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
799 is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
800 is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
802 # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
803 t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
804 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
806 C4::Overdues::UpdateFine(
808 issue_id => $issue->id(),
809 itemnumber => $item_1->itemnumber,
810 borrowernumber => $renewing_borrower->{borrowernumber},
811 amount => 15.00,
812 type => q{},
813 due => Koha::DateUtils::output_pref($datedue)
817 my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower->{borrowernumber} })->next();
818 is( $line->accounttype, 'FU', 'Account line type is FU' );
819 is( $line->lastincrement, '15.000000', 'Account line last increment is 15.00' );
820 is( $line->amountoutstanding, '15.000000', 'Account line amount outstanding is 15.00' );
821 is( $line->amount, '15.000000', 'Account line amount is 15.00' );
822 is( $line->issue_id, $issue->id, 'Account line issue id matches' );
824 my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
825 is( $offset->type, 'Fine', 'Account offset type is Fine' );
826 is( $offset->amount, '15.000000', 'Account offset amount is 15.00' );
828 t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
829 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
831 LostItem( $item_1->itemnumber, 'test', 1 );
833 $line = Koha::Account::Lines->find($line->id);
834 is( $line->accounttype, 'F', 'Account type correctly changed from FU to F' );
836 my $item = Koha::Items->find($item_1->itemnumber);
837 ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
838 my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
839 is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
841 my $total_due = $dbh->selectrow_array(
842 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
843 undef, $renewing_borrower->{borrowernumber}
846 is( $total_due, '15.000000', 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
848 C4::Context->dbh->do("DELETE FROM accountlines");
850 C4::Overdues::UpdateFine(
852 issue_id => $issue2->id(),
853 itemnumber => $item_2->itemnumber,
854 borrowernumber => $renewing_borrower->{borrowernumber},
855 amount => 15.00,
856 type => q{},
857 due => Koha::DateUtils::output_pref($datedue)
861 LostItem( $item_2->itemnumber, 'test', 0 );
863 my $item2 = Koha::Items->find($item_2->itemnumber);
864 ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
865 ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
867 $total_due = $dbh->selectrow_array(
868 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
869 undef, $renewing_borrower->{borrowernumber}
872 ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
874 my $future = dt_from_string();
875 $future->add( days => 7 );
876 my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
877 ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
879 # Users cannot renew any item if there is an overdue item
880 t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
881 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
882 is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
883 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
884 is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
886 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
887 $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
888 LostItem( $item_3->itemnumber, 'test', 0 );
889 my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
890 is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
894 # GetUpcomingDueIssues tests
895 my $branch = $library2->{branchcode};
897 #Create another record
898 my $biblio2 = $builder->build_sample_biblio();
900 #Create third item
901 my $item_1 = Koha::Items->find($reused_itemnumber_1);
902 my $item_2 = Koha::Items->find($reused_itemnumber_2);
903 my $item_3 = $builder->build_sample_item(
905 biblionumber => $biblio2->biblionumber,
906 library => $branch,
907 itype => $itemtype,
912 # Create a borrower
913 my %a_borrower_data = (
914 firstname => 'Fridolyn',
915 surname => 'SOMERS',
916 categorycode => $patron_category->{categorycode},
917 branchcode => $branch,
920 my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
921 my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
923 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
924 my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
925 my $today = DateTime->today(time_zone => C4::Context->tz());
927 my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
928 my $datedue = dt_from_string( $issue->date_due() );
929 my $issue2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
930 my $datedue2 = dt_from_string( $issue->date_due() );
932 my $upcoming_dues;
934 # GetUpcomingDueIssues tests
935 for my $i(0..1) {
936 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
937 is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
940 #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
941 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
942 is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
944 for my $i(3..5) {
945 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
946 is ( scalar( @$upcoming_dues ), 1,
947 "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
950 # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
952 my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
954 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
955 is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
957 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
958 is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
960 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
961 is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
963 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
964 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
966 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
967 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
969 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
970 is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
975 my $branch = $library2->{branchcode};
977 my $biblio = $builder->build_sample_biblio();
979 #Create third item
980 my $item = $builder->build_sample_item(
982 biblionumber => $biblio->biblionumber,
983 library => $branch,
984 itype => $itemtype,
988 # Create a borrower
989 my %a_borrower_data = (
990 firstname => 'Kyle',
991 surname => 'Hall',
992 categorycode => $patron_category->{categorycode},
993 branchcode => $branch,
996 my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
998 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
999 my $issue = AddIssue( $borrower, $item->barcode );
1000 UpdateFine(
1002 issue_id => $issue->id(),
1003 itemnumber => $item->itemnumber,
1004 borrowernumber => $borrowernumber,
1005 amount => 0,
1006 type => q{}
1010 my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1011 my $count = $hr->{count};
1013 is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1017 $dbh->do('DELETE FROM issues');
1018 $dbh->do('DELETE FROM items');
1019 $dbh->do('DELETE FROM issuingrules');
1020 Koha::CirculationRules->search()->delete();
1021 $dbh->do(
1023 INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, issuelength, lengthunit, renewalsallowed, renewalperiod,
1024 norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
1027 '*', '*', '*', 25,
1028 14, 'days',
1029 1, 7,
1030 undef, 0,
1031 .10, 1
1033 Koha::CirculationRules->set_rules(
1035 categorycode => '*',
1036 itemtype => '*',
1037 branchcode => '*',
1038 rules => {
1039 maxissueqty => 20
1043 my $biblio = $builder->build_sample_biblio();
1045 my $item_1 = $builder->build_sample_item(
1047 biblionumber => $biblio->biblionumber,
1048 library => $library2->{branchcode},
1049 itype => $itemtype,
1053 my $item_2= $builder->build_sample_item(
1055 biblionumber => $biblio->biblionumber,
1056 library => $library2->{branchcode},
1057 itype => $itemtype,
1061 my $borrowernumber1 = Koha::Patron->new({
1062 firstname => 'Kyle',
1063 surname => 'Hall',
1064 categorycode => $patron_category->{categorycode},
1065 branchcode => $library2->{branchcode},
1066 })->store->borrowernumber;
1067 my $borrowernumber2 = Koha::Patron->new({
1068 firstname => 'Chelsea',
1069 surname => 'Hall',
1070 categorycode => $patron_category->{categorycode},
1071 branchcode => $library2->{branchcode},
1072 })->store->borrowernumber;
1074 my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1075 my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1077 my $issue = AddIssue( $borrower1, $item_1->barcode );
1079 my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1080 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1082 AddReserve(
1083 $library2->{branchcode}, $borrowernumber2, $biblio->biblionumber,
1084 '', 1, undef, undef, '',
1085 undef, undef, undef
1088 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1089 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1090 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1091 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1093 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1094 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1095 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1096 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1098 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1099 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1100 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1101 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1103 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1104 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1105 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1106 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1108 # Setting item not checked out to be not for loan but holdable
1109 ModItem({ notforloan => -1 }, $biblio->biblionumber, $item_2->itemnumber);
1111 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1112 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' );
1116 # Don't allow renewing onsite checkout
1117 my $branch = $library->{branchcode};
1119 #Create another record
1120 my $biblio = $builder->build_sample_biblio();
1122 my $item = $builder->build_sample_item(
1124 biblionumber => $biblio->biblionumber,
1125 library => $branch,
1126 itype => $itemtype,
1130 my $borrowernumber = Koha::Patron->new({
1131 firstname => 'fn',
1132 surname => 'dn',
1133 categorycode => $patron_category->{categorycode},
1134 branchcode => $branch,
1135 })->store->borrowernumber;
1137 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1139 my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1140 my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $item->itemnumber );
1141 is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1142 is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1146 my $library = $builder->build({ source => 'Branch' });
1148 my $biblio = $builder->build_sample_biblio();
1150 my $item = $builder->build_sample_item(
1152 biblionumber => $biblio->biblionumber,
1153 library => $library->{branchcode},
1154 itype => $itemtype,
1158 my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1160 my $issue = AddIssue( $patron, $item->barcode );
1161 UpdateFine(
1163 issue_id => $issue->id(),
1164 itemnumber => $item->itemnumber,
1165 borrowernumber => $patron->{borrowernumber},
1166 amount => 1,
1167 type => q{}
1170 UpdateFine(
1172 issue_id => $issue->id(),
1173 itemnumber => $item->itemnumber,
1174 borrowernumber => $patron->{borrowernumber},
1175 amount => 2,
1176 type => q{}
1179 is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1182 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1183 plan tests => 24;
1185 my $homebranch = $builder->build( { source => 'Branch' } );
1186 my $holdingbranch = $builder->build( { source => 'Branch' } );
1187 my $otherbranch = $builder->build( { source => 'Branch' } );
1188 my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1189 my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1191 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1192 my $item = $builder->build(
1193 { source => 'Item',
1194 value => {
1195 homebranch => $homebranch->{branchcode},
1196 holdingbranch => $holdingbranch->{branchcode},
1197 biblionumber => $biblioitem->{biblionumber}
1202 set_userenv($holdingbranch);
1204 my $issue = AddIssue( $patron_1->unblessed, $item->{barcode} );
1205 is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
1207 my ( $error, $question, $alerts );
1209 # AllowReturnToBranch == anywhere
1210 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1211 ## Test that unknown barcodes don't generate internal server errors
1212 set_userenv($homebranch);
1213 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1214 ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1215 ## Can be issued from homebranch
1216 set_userenv($homebranch);
1217 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1218 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1219 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1220 ## Can be issued from holdingbranch
1221 set_userenv($holdingbranch);
1222 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1223 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1224 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1225 ## Can be issued from another branch
1226 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1227 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1228 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1230 # AllowReturnToBranch == holdingbranch
1231 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1232 ## Cannot be issued from homebranch
1233 set_userenv($homebranch);
1234 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1235 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1236 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1237 is( $error->{branch_to_return}, $holdingbranch->{branchcode} );
1238 ## Can be issued from holdinbranch
1239 set_userenv($holdingbranch);
1240 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1241 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1242 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1243 ## Cannot be issued from another branch
1244 set_userenv($otherbranch);
1245 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1246 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1247 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1248 is( $error->{branch_to_return}, $holdingbranch->{branchcode} );
1250 # AllowReturnToBranch == homebranch
1251 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1252 ## Can be issued from holdinbranch
1253 set_userenv($homebranch);
1254 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1255 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1256 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1257 ## Cannot be issued from holdinbranch
1258 set_userenv($holdingbranch);
1259 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1260 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1261 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1262 is( $error->{branch_to_return}, $homebranch->{branchcode} );
1263 ## Cannot be issued from holdinbranch
1264 set_userenv($otherbranch);
1265 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1266 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1267 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1268 is( $error->{branch_to_return}, $homebranch->{branchcode} );
1270 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1273 subtest 'AddIssue & AllowReturnToBranch' => sub {
1274 plan tests => 9;
1276 my $homebranch = $builder->build( { source => 'Branch' } );
1277 my $holdingbranch = $builder->build( { source => 'Branch' } );
1278 my $otherbranch = $builder->build( { source => 'Branch' } );
1279 my $patron_1 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1280 my $patron_2 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1282 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1283 my $item = $builder->build(
1284 { source => 'Item',
1285 value => {
1286 homebranch => $homebranch->{branchcode},
1287 holdingbranch => $holdingbranch->{branchcode},
1288 notforloan => 0,
1289 itemlost => 0,
1290 withdrawn => 0,
1291 biblionumber => $biblioitem->{biblionumber}
1296 set_userenv($holdingbranch);
1298 my $ref_issue = 'Koha::Checkout';
1299 my $issue = AddIssue( $patron_1, $item->{barcode} );
1301 my ( $error, $question, $alerts );
1303 # AllowReturnToBranch == homebranch
1304 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1305 ## Can be issued from homebranch
1306 set_userenv($homebranch);
1307 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1308 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1309 ## Can be issued from holdinbranch
1310 set_userenv($holdingbranch);
1311 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1312 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1313 ## Can be issued from another branch
1314 set_userenv($otherbranch);
1315 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1316 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1318 # AllowReturnToBranch == holdinbranch
1319 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1320 ## Cannot be issued from homebranch
1321 set_userenv($homebranch);
1322 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1323 ## Can be issued from holdingbranch
1324 set_userenv($holdingbranch);
1325 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1326 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1327 ## Cannot be issued from another branch
1328 set_userenv($otherbranch);
1329 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1331 # AllowReturnToBranch == homebranch
1332 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1333 ## Can be issued from homebranch
1334 set_userenv($homebranch);
1335 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1336 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1337 ## Cannot be issued from holdinbranch
1338 set_userenv($holdingbranch);
1339 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1340 ## Cannot be issued from another branch
1341 set_userenv($otherbranch);
1342 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1343 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1346 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1347 plan tests => 8;
1349 my $library = $builder->build( { source => 'Branch' } );
1350 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1352 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1353 my $item_1 = $builder->build(
1354 { source => 'Item',
1355 value => {
1356 homebranch => $library->{branchcode},
1357 holdingbranch => $library->{branchcode},
1358 biblionumber => $biblioitem_1->{biblionumber}
1362 my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1363 my $item_2 = $builder->build(
1364 { source => 'Item',
1365 value => {
1366 homebranch => $library->{branchcode},
1367 holdingbranch => $library->{branchcode},
1368 biblionumber => $biblioitem_2->{biblionumber}
1373 my ( $error, $question, $alerts );
1375 # Patron cannot issue item_1, they have overdues
1376 my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1377 my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, $yesterday ); # Add an overdue
1379 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1380 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1381 is( keys(%$error) + keys(%$alerts), 0, 'No key for error and alert' . str($error, $question, $alerts) );
1382 is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
1384 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1385 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1386 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1387 is( $error->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
1389 # Patron cannot issue item_1, they are debarred
1390 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1391 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
1392 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1393 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1394 is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
1396 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
1397 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1398 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1399 is( $error->{USERBLOCKEDNOENDDATE}, '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
1402 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
1403 plan tests => 1;
1405 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1406 my $patron_category_x = $builder->build_object(
1408 class => 'Koha::Patron::Categories',
1409 value => { category_type => 'X' }
1412 my $patron = $builder->build_object(
1414 class => 'Koha::Patrons',
1415 value => {
1416 categorycode => $patron_category_x->categorycode,
1417 gonenoaddress => undef,
1418 lost => undef,
1419 debarred => undef,
1420 borrowernotes => ""
1424 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1425 my $item_1 = $builder->build(
1427 source => 'Item',
1428 value => {
1429 homebranch => $library->branchcode,
1430 holdingbranch => $library->branchcode,
1431 biblionumber => $biblioitem_1->{biblionumber}
1436 my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->{barcode} );
1437 is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
1439 # TODO There are other tests to provide here
1442 subtest 'MultipleReserves' => sub {
1443 plan tests => 3;
1445 my $biblio = $builder->build_sample_biblio();
1447 my $branch = $library2->{branchcode};
1449 my $item_1 = $builder->build_sample_item(
1451 biblionumber => $biblio->biblionumber,
1452 library => $branch,
1453 replacementprice => 12.00,
1454 itype => $itemtype,
1458 my $item_2 = $builder->build_sample_item(
1460 biblionumber => $biblio->biblionumber,
1461 library => $branch,
1462 replacementprice => 12.00,
1463 itype => $itemtype,
1467 my $bibitems = '';
1468 my $priority = '1';
1469 my $resdate = undef;
1470 my $expdate = undef;
1471 my $notes = '';
1472 my $checkitem = undef;
1473 my $found = undef;
1475 my %renewing_borrower_data = (
1476 firstname => 'John',
1477 surname => 'Renewal',
1478 categorycode => $patron_category->{categorycode},
1479 branchcode => $branch,
1481 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
1482 my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
1483 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
1484 my $datedue = dt_from_string( $issue->date_due() );
1485 is (defined $issue->date_due(), 1, "item 1 checked out");
1486 my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
1488 my %reserving_borrower_data1 = (
1489 firstname => 'Katrin',
1490 surname => 'Reservation',
1491 categorycode => $patron_category->{categorycode},
1492 branchcode => $branch,
1494 my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
1495 AddReserve(
1496 $branch, $reserving_borrowernumber1, $biblio->biblionumber,
1497 $bibitems, $priority, $resdate, $expdate, $notes,
1498 'a title', $checkitem, $found
1501 my %reserving_borrower_data2 = (
1502 firstname => 'Kirk',
1503 surname => 'Reservation',
1504 categorycode => $patron_category->{categorycode},
1505 branchcode => $branch,
1507 my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
1508 AddReserve(
1509 $branch, $reserving_borrowernumber2, $biblio->biblionumber,
1510 $bibitems, $priority, $resdate, $expdate, $notes,
1511 'a title', $checkitem, $found
1515 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1516 is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
1519 my $item_3 = $builder->build_sample_item(
1521 biblionumber => $biblio->biblionumber,
1522 library => $branch,
1523 replacementprice => 12.00,
1524 itype => $itemtype,
1529 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1530 is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
1534 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
1535 plan tests => 5;
1537 my $library = $builder->build( { source => 'Branch' } );
1538 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1540 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1541 my $biblionumber = $biblioitem->{biblionumber};
1542 my $item_1 = $builder->build(
1543 { source => 'Item',
1544 value => {
1545 homebranch => $library->{branchcode},
1546 holdingbranch => $library->{branchcode},
1547 biblionumber => $biblionumber,
1551 my $item_2 = $builder->build(
1552 { source => 'Item',
1553 value => {
1554 homebranch => $library->{branchcode},
1555 holdingbranch => $library->{branchcode},
1556 biblionumber => $biblionumber,
1561 my ( $error, $question, $alerts );
1562 my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, dt_from_string->add( days => 1 ) );
1564 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1565 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1566 is( keys(%$error) + keys(%$alerts), 0, 'No error or alert should be raised' . str($error, $question, $alerts) );
1567 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) );
1569 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1570 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1571 is( keys(%$error) + keys(%$question) + keys(%$alerts), 0, 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1' . str($error, $question, $alerts) );
1573 # Add a subscription
1574 Koha::Subscription->new({ biblionumber => $biblionumber })->store;
1576 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1577 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1578 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) );
1580 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1581 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1582 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) );
1585 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
1586 plan tests => 8;
1588 my $library = $builder->build( { source => 'Branch' } );
1589 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1591 # Add 2 items
1592 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1593 my $item_1 = $builder->build(
1595 source => 'Item',
1596 value => {
1597 homebranch => $library->{branchcode},
1598 holdingbranch => $library->{branchcode},
1599 notforloan => 0,
1600 itemlost => 0,
1601 withdrawn => 0,
1602 biblionumber => $biblioitem_1->{biblionumber}
1606 my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1607 my $item_2 = $builder->build(
1609 source => 'Item',
1610 value => {
1611 homebranch => $library->{branchcode},
1612 holdingbranch => $library->{branchcode},
1613 notforloan => 0,
1614 itemlost => 0,
1615 withdrawn => 0,
1616 biblionumber => $biblioitem_2->{biblionumber}
1621 # And the issuing rule
1622 Koha::IssuingRules->search->delete;
1623 my $rule = Koha::IssuingRule->new(
1625 categorycode => '*',
1626 itemtype => '*',
1627 branchcode => '*',
1628 issuelength => 1,
1629 firstremind => 1, # 1 day of grace
1630 finedays => 2, # 2 days of fine per day of overdue
1631 lengthunit => 'days',
1634 $rule->store();
1636 # Patron cannot issue item_1, they have overdues
1637 my $five_days_ago = dt_from_string->subtract( days => 5 );
1638 my $ten_days_ago = dt_from_string->subtract( days => 10 );
1639 AddIssue( $patron, $item_1->{barcode}, $five_days_ago ); # Add an overdue
1640 AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1641 ; # Add another overdue
1643 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
1644 AddReturn( $item_1->{barcode}, $library->{branchcode},
1645 undef, undef, dt_from_string );
1646 my $debarments = Koha::Patron::Debarments::GetDebarments(
1647 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1648 is( scalar(@$debarments), 1 );
1650 # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
1651 # Same for the others
1652 my $expected_expiration = output_pref(
1654 dt => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1655 dateformat => 'sql',
1656 dateonly => 1
1659 is( $debarments->[0]->{expiration}, $expected_expiration );
1661 AddReturn( $item_2->{barcode}, $library->{branchcode},
1662 undef, undef, dt_from_string );
1663 $debarments = Koha::Patron::Debarments::GetDebarments(
1664 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1665 is( scalar(@$debarments), 1 );
1666 $expected_expiration = output_pref(
1668 dt => dt_from_string->add( days => ( 10 - 1 ) * 2 ),
1669 dateformat => 'sql',
1670 dateonly => 1
1673 is( $debarments->[0]->{expiration}, $expected_expiration );
1675 Koha::Patron::Debarments::DelUniqueDebarment(
1676 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1678 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
1679 AddIssue( $patron, $item_1->{barcode}, $five_days_ago ); # Add an overdue
1680 AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1681 ; # Add another overdue
1682 AddReturn( $item_1->{barcode}, $library->{branchcode},
1683 undef, undef, dt_from_string );
1684 $debarments = Koha::Patron::Debarments::GetDebarments(
1685 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1686 is( scalar(@$debarments), 1 );
1687 $expected_expiration = output_pref(
1689 dt => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1690 dateformat => 'sql',
1691 dateonly => 1
1694 is( $debarments->[0]->{expiration}, $expected_expiration );
1696 AddReturn( $item_2->{barcode}, $library->{branchcode},
1697 undef, undef, dt_from_string );
1698 $debarments = Koha::Patron::Debarments::GetDebarments(
1699 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1700 is( scalar(@$debarments), 1 );
1701 $expected_expiration = output_pref(
1703 dt => dt_from_string->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
1704 dateformat => 'sql',
1705 dateonly => 1
1708 is( $debarments->[0]->{expiration}, $expected_expiration );
1711 subtest 'AddReturn + suspension_chargeperiod' => sub {
1712 plan tests => 21;
1714 my $library = $builder->build( { source => 'Branch' } );
1715 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1717 # Add 2 items
1718 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1719 my $item_1 = $builder->build(
1721 source => 'Item',
1722 value => {
1723 homebranch => $library->{branchcode},
1724 holdingbranch => $library->{branchcode},
1725 notforloan => 0,
1726 itemlost => 0,
1727 withdrawn => 0,
1728 biblionumber => $biblioitem_1->{biblionumber}
1733 # And the issuing rule
1734 Koha::IssuingRules->search->delete;
1735 my $rule = Koha::IssuingRule->new(
1737 categorycode => '*',
1738 itemtype => '*',
1739 branchcode => '*',
1740 issuelength => 1,
1741 firstremind => 0, # 0 day of grace
1742 finedays => 2, # 2 days of fine per day of overdue
1743 suspension_chargeperiod => 1,
1744 lengthunit => 'days',
1747 $rule->store();
1749 my $five_days_ago = dt_from_string->subtract( days => 5 );
1750 # We want to charge 2 days every day, without grace
1751 # With 5 days of overdue: 5 * Z
1752 my $expected_expiration = dt_from_string->add( days => ( 5 * 2 ) / 1 );
1753 test_debarment_on_checkout(
1755 item => $item_1,
1756 library => $library,
1757 patron => $patron,
1758 due_date => $five_days_ago,
1759 expiration_date => $expected_expiration,
1763 # We want to charge 2 days every 2 days, without grace
1764 # With 5 days of overdue: (5 * 2) / 2
1765 $rule->suspension_chargeperiod(2)->store;
1766 $expected_expiration = dt_from_string->add( days => floor( 5 * 2 ) / 2 );
1767 test_debarment_on_checkout(
1769 item => $item_1,
1770 library => $library,
1771 patron => $patron,
1772 due_date => $five_days_ago,
1773 expiration_date => $expected_expiration,
1777 # We want to charge 2 days every 3 days, with 1 day of grace
1778 # With 5 days of overdue: ((5-1) / 3 ) * 2
1779 $rule->suspension_chargeperiod(3)->store;
1780 $rule->firstremind(1)->store;
1781 $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
1782 test_debarment_on_checkout(
1784 item => $item_1,
1785 library => $library,
1786 patron => $patron,
1787 due_date => $five_days_ago,
1788 expiration_date => $expected_expiration,
1792 # Use finesCalendar to know if holiday must be skipped to calculate the due date
1793 # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
1794 $rule->finedays(2)->store;
1795 $rule->suspension_chargeperiod(1)->store;
1796 $rule->firstremind(0)->store;
1797 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
1799 # Adding a holiday 2 days ago
1800 my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
1801 my $two_days_ago = dt_from_string->subtract( days => 2 );
1802 $calendar->insert_single_holiday(
1803 day => $two_days_ago->day,
1804 month => $two_days_ago->month,
1805 year => $two_days_ago->year,
1806 title => 'holidayTest-2d',
1807 description => 'holidayDesc 2 days ago'
1809 # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
1810 $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
1811 test_debarment_on_checkout(
1813 item => $item_1,
1814 library => $library,
1815 patron => $patron,
1816 due_date => $five_days_ago,
1817 expiration_date => $expected_expiration,
1821 # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
1822 my $two_days_ahead = dt_from_string->add( days => 2 );
1823 $calendar->insert_single_holiday(
1824 day => $two_days_ahead->day,
1825 month => $two_days_ahead->month,
1826 year => $two_days_ahead->year,
1827 title => 'holidayTest+2d',
1828 description => 'holidayDesc 2 days ahead'
1831 # Same as above, but we should skip D+2
1832 $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
1833 test_debarment_on_checkout(
1835 item => $item_1,
1836 library => $library,
1837 patron => $patron,
1838 due_date => $five_days_ago,
1839 expiration_date => $expected_expiration,
1843 # Adding another holiday, day of expiration date
1844 my $expected_expiration_dt = dt_from_string($expected_expiration);
1845 $calendar->insert_single_holiday(
1846 day => $expected_expiration_dt->day,
1847 month => $expected_expiration_dt->month,
1848 year => $expected_expiration_dt->year,
1849 title => 'holidayTest_exp',
1850 description => 'holidayDesc on expiration date'
1852 # Expiration date will be the day after
1853 test_debarment_on_checkout(
1855 item => $item_1,
1856 library => $library,
1857 patron => $patron,
1858 due_date => $five_days_ago,
1859 expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
1863 test_debarment_on_checkout(
1865 item => $item_1,
1866 library => $library,
1867 patron => $patron,
1868 return_date => dt_from_string->add(days => 5),
1869 expiration_date => dt_from_string->add(days => 5 + (5 * 2 - 1) ),
1874 subtest 'AddReturn | is_overdue' => sub {
1875 plan tests => 5;
1877 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
1878 t::lib::Mocks::mock_preference('finesMode', 'production');
1879 t::lib::Mocks::mock_preference('MaxFine', '100');
1881 my $library = $builder->build( { source => 'Branch' } );
1882 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1884 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1885 my $item = $builder->build(
1887 source => 'Item',
1888 value => {
1889 homebranch => $library->{branchcode},
1890 holdingbranch => $library->{branchcode},
1891 notforloan => 0,
1892 itemlost => 0,
1893 withdrawn => 0,
1894 biblionumber => $biblioitem->{biblionumber},
1899 Koha::IssuingRules->search->delete;
1900 my $rule = Koha::IssuingRule->new(
1902 categorycode => '*',
1903 itemtype => '*',
1904 branchcode => '*',
1905 issuelength => 6,
1906 lengthunit => 'days',
1907 fine => 1, # Charge 1 every day of overdue
1908 chargeperiod => 1,
1911 $rule->store();
1913 my $one_day_ago = dt_from_string->subtract( days => 1 );
1914 my $five_days_ago = dt_from_string->subtract( days => 5 );
1915 my $ten_days_ago = dt_from_string->subtract( days => 10 );
1916 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1918 # No date specify, today will be used
1919 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1920 AddReturn( $item->{barcode}, $library->{branchcode} );
1921 is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
1922 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1924 # specify return date 5 days before => no overdue
1925 AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
1926 AddReturn( $item->{barcode}, $library->{branchcode}, undef, undef, $ten_days_ago );
1927 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
1928 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1930 # specify return date 5 days later => overdue
1931 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1932 AddReturn( $item->{barcode}, $library->{branchcode}, undef, undef, $five_days_ago );
1933 is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
1934 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1936 # specify dropbox date 5 days before => no overdue
1937 AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
1938 AddReturn( $item->{barcode}, $library->{branchcode}, undef, 1, undef, $ten_days_ago );
1939 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
1940 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1942 # specify dropbox date 5 days later => overdue, or... not
1943 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1944 AddReturn( $item->{barcode}, $library->{branchcode}, undef, 1, undef, $five_days_ago );
1945 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
1946 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1949 subtest '_FixAccountForLostAndReturned' => sub {
1951 plan tests => 5;
1953 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
1954 t::lib::Mocks::mock_preference( 'WhenLostForgiveFine', 0 );
1956 my $processfee_amount = 20;
1957 my $replacement_amount = 99.00;
1958 my $item_type = $builder->build_object(
1959 { class => 'Koha::ItemTypes',
1960 value => {
1961 notforloan => undef,
1962 rentalcharge => 0,
1963 defaultreplacecost => undef,
1964 processfee => $processfee_amount,
1965 rentalcharge_daily => 0,
1969 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1971 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Daria' });
1973 subtest 'Full write-off tests' => sub {
1975 plan tests => 10;
1977 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1979 my $item = $builder->build_sample_item(
1981 biblionumber => $biblio->biblionumber,
1982 library => $library->branchcode,
1983 replacementprice => $replacement_amount,
1984 itype => $item_type->itemtype,
1988 AddIssue( $patron->unblessed, $item->barcode );
1990 # Simulate item marked as lost
1991 ModItem( { itemlost => 3 }, $biblio->biblionumber, $item->itemnumber );
1992 LostItem( $item->itemnumber, 1 );
1994 my $processing_fee_lines = Koha::Account::Lines->search(
1995 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
1996 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
1997 my $processing_fee_line = $processing_fee_lines->next;
1998 is( $processing_fee_line->amount + 0,
1999 $processfee_amount, 'The right PF amount is generated' );
2000 is( $processing_fee_line->amountoutstanding + 0,
2001 $processfee_amount, 'The right PF amountoutstanding is generated' );
2003 my $lost_fee_lines = Koha::Account::Lines->search(
2004 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2005 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2006 my $lost_fee_line = $lost_fee_lines->next;
2007 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2008 is( $lost_fee_line->amountoutstanding + 0,
2009 $replacement_amount, 'The right L amountoutstanding is generated' );
2011 my $account = $patron->account;
2012 my $debts = $account->outstanding_debits;
2014 # Write off the debt
2015 my $credit = $account->add_credit(
2016 { amount => $account->balance,
2017 type => 'writeoff'
2020 $credit->apply( { debits => $debts, offset_type => 'Writeoff' } );
2022 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2023 is( $credit_return_id, undef, 'No CR account line added' );
2025 $lost_fee_line->discard_changes; # reload from DB
2026 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2027 is( $lost_fee_line->accounttype,
2028 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2030 is( $patron->account->balance, -0, 'The patron balance is 0, everything was written off' );
2033 subtest 'Full payment tests' => sub {
2035 plan tests => 12;
2037 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2039 my $item = $builder->build_sample_item(
2041 biblionumber => $biblio->biblionumber,
2042 library => $library->branchcode,
2043 replacementprice => $replacement_amount,
2044 itype => $item_type->itemtype
2048 AddIssue( $patron->unblessed, $item->barcode );
2050 # Simulate item marked as lost
2051 ModItem( { itemlost => 1 }, $biblio->biblionumber, $item->itemnumber );
2052 LostItem( $item->itemnumber, 1 );
2054 my $processing_fee_lines = Koha::Account::Lines->search(
2055 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2056 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2057 my $processing_fee_line = $processing_fee_lines->next;
2058 is( $processing_fee_line->amount + 0,
2059 $processfee_amount, 'The right PF amount is generated' );
2060 is( $processing_fee_line->amountoutstanding + 0,
2061 $processfee_amount, 'The right PF amountoutstanding is generated' );
2063 my $lost_fee_lines = Koha::Account::Lines->search(
2064 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2065 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2066 my $lost_fee_line = $lost_fee_lines->next;
2067 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2068 is( $lost_fee_line->amountoutstanding + 0,
2069 $replacement_amount, 'The right L amountountstanding is generated' );
2071 my $account = $patron->account;
2072 my $debts = $account->outstanding_debits;
2074 # Write off the debt
2075 my $credit = $account->add_credit(
2076 { amount => $account->balance,
2077 type => 'payment'
2080 $credit->apply( { debits => $debts, offset_type => 'Payment' } );
2082 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2083 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2085 is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2086 is( $credit_return->amount + 0,
2087 -99.00, 'The account line of type CR has an amount of -99' );
2088 is( $credit_return->amountoutstanding + 0,
2089 -99.00, 'The account line of type CR has an amountoutstanding of -99' );
2091 $lost_fee_line->discard_changes;
2092 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2093 is( $lost_fee_line->accounttype,
2094 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2096 is( $patron->account->balance,
2097 -99, 'The patron balance is -99, a credit that equals the lost fee payment' );
2100 subtest 'Test without payment or write off' => sub {
2102 plan tests => 12;
2104 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2106 my $item = $builder->build_sample_item(
2108 biblionumber => $biblio->biblionumber,
2109 library => $library->branchcode,
2110 replacementprice => 23.00,
2111 replacementprice => $replacement_amount,
2112 itype => $item_type->itemtype
2116 AddIssue( $patron->unblessed, $item->barcode );
2118 # Simulate item marked as lost
2119 ModItem( { itemlost => 3 }, $biblio->biblionumber, $item->itemnumber );
2120 LostItem( $item->itemnumber, 1 );
2122 my $processing_fee_lines = Koha::Account::Lines->search(
2123 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2124 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2125 my $processing_fee_line = $processing_fee_lines->next;
2126 is( $processing_fee_line->amount + 0,
2127 $processfee_amount, 'The right PF amount is generated' );
2128 is( $processing_fee_line->amountoutstanding + 0,
2129 $processfee_amount, 'The right PF amountoutstanding is generated' );
2131 my $lost_fee_lines = Koha::Account::Lines->search(
2132 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2133 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2134 my $lost_fee_line = $lost_fee_lines->next;
2135 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2136 is( $lost_fee_line->amountoutstanding + 0,
2137 $replacement_amount, 'The right L amountountstanding is generated' );
2139 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2140 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2142 is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2143 is( $credit_return->amount + 0, -99.00, 'The account line of type CR has an amount of -99' );
2144 is( $credit_return->amountoutstanding + 0, 0, 'The account line of type CR has an amountoutstanding of 0' );
2146 $lost_fee_line->discard_changes;
2147 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2148 is( $lost_fee_line->accounttype, 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2150 is( $patron->account->balance, 20, 'The patron balance is 20, still owes the processing fee' );
2153 subtest 'Test with partial payement and write off, and remaining debt' => sub {
2155 plan tests => 15;
2157 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2158 my $item = $builder->build_sample_item(
2160 biblionumber => $biblio->biblionumber,
2161 library => $library->branchcode,
2162 replacementprice => $replacement_amount,
2163 itype => $item_type->itemtype
2167 AddIssue( $patron->unblessed, $item->barcode );
2169 # Simulate item marked as lost
2170 ModItem( { itemlost => 1 }, $biblio->biblionumber, $item->itemnumber );
2171 LostItem( $item->itemnumber, 1 );
2173 my $processing_fee_lines = Koha::Account::Lines->search(
2174 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2175 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2176 my $processing_fee_line = $processing_fee_lines->next;
2177 is( $processing_fee_line->amount + 0,
2178 $processfee_amount, 'The right PF amount is generated' );
2179 is( $processing_fee_line->amountoutstanding + 0,
2180 $processfee_amount, 'The right PF amountoutstanding is generated' );
2182 my $lost_fee_lines = Koha::Account::Lines->search(
2183 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2184 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2185 my $lost_fee_line = $lost_fee_lines->next;
2186 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2187 is( $lost_fee_line->amountoutstanding + 0,
2188 $replacement_amount, 'The right L amountountstanding is generated' );
2190 my $account = $patron->account;
2191 is( $account->balance, $processfee_amount + $replacement_amount, 'Balance is PF + L' );
2193 # Partially pay fee
2194 my $payment_amount = 27;
2195 my $payment = $account->add_credit(
2196 { amount => $payment_amount,
2197 type => 'payment'
2201 $payment->apply( { debits => $lost_fee_lines->reset, offset_type => 'Payment' } );
2203 # Partially write off fee
2204 my $write_off_amount = 25;
2205 my $write_off = $account->add_credit(
2206 { amount => $write_off_amount,
2207 type => 'writeoff'
2210 $write_off->apply( { debits => $lost_fee_lines->reset, offset_type => 'Writeoff' } );
2212 is( $account->balance,
2213 $processfee_amount + $replacement_amount - $payment_amount - $write_off_amount,
2214 'Payment and write off applied'
2217 # Store the amountoutstanding value
2218 $lost_fee_line->discard_changes;
2219 my $outstanding = $lost_fee_line->amountoutstanding;
2221 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2222 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2224 is( $account->balance, $processfee_amount - $payment_amount, 'Balance is PF - payment (CR)' );
2226 $lost_fee_line->discard_changes;
2227 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2228 is( $lost_fee_line->accounttype,
2229 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2231 is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2232 is( $credit_return->amount + 0,
2233 ($payment_amount + $outstanding ) * -1,
2234 'The account line of type CR has an amount equal to the payment + outstanding'
2236 is( $credit_return->amountoutstanding + 0,
2237 $payment_amount * -1,
2238 'The account line of type CR has an amountoutstanding equal to the payment'
2241 is( $account->balance,
2242 $processfee_amount - $payment_amount,
2243 'The patron balance is the difference between the PF and the credit'
2247 subtest 'Partial payement, existing debits and AccountAutoReconcile' => sub {
2249 plan tests => 8;
2251 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2252 my $barcode = 'KD123456793';
2253 my $replacement_amount = 100;
2254 my $processfee_amount = 20;
2256 my $item_type = $builder->build_object(
2257 { class => 'Koha::ItemTypes',
2258 value => {
2259 notforloan => undef,
2260 rentalcharge => 0,
2261 defaultreplacecost => undef,
2262 processfee => 0,
2263 rentalcharge_daily => 0,
2267 my ( undef, undef, $item_id ) = AddItem(
2268 { homebranch => $library->branchcode,
2269 holdingbranch => $library->branchcode,
2270 barcode => $barcode,
2271 replacementprice => $replacement_amount,
2272 itype => $item_type->itemtype
2274 $biblio->biblionumber
2277 AddIssue( $patron->unblessed, $barcode );
2279 # Simulate item marked as lost
2280 ModItem( { itemlost => 1 }, $biblio->biblionumber, $item_id );
2281 LostItem( $item_id, 1 );
2283 my $lost_fee_lines = Koha::Account::Lines->search(
2284 { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'L' } );
2285 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2286 my $lost_fee_line = $lost_fee_lines->next;
2287 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2288 is( $lost_fee_line->amountoutstanding + 0,
2289 $replacement_amount, 'The right L amountountstanding is generated' );
2291 my $account = $patron->account;
2292 is( $account->balance, $replacement_amount, 'Balance is L' );
2294 # Partially pay fee
2295 my $payment_amount = 27;
2296 my $payment = $account->add_credit(
2297 { amount => $payment_amount,
2298 type => 'payment'
2301 $payment->apply({ debits => $lost_fee_lines->reset, offset_type => 'Payment' });
2303 is( $account->balance,
2304 $replacement_amount - $payment_amount,
2305 'Payment applied'
2308 # TODO use add_debit when time comes
2309 my $manual_debit_amount = 80;
2310 C4::Accounts::manualinvoice( $patron->id, undef, undef, 'FU', $manual_debit_amount );
2312 is( $account->balance, $manual_debit_amount + $replacement_amount - $payment_amount, 'Manual debit applied' );
2314 t::lib::Mocks::mock_preference( 'AccountAutoReconcile', 1 );
2316 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item_id, $patron->id );
2317 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2319 is( $account->balance, $manual_debit_amount - $payment_amount, 'Balance is PF - payment (CR)' );
2321 my $manual_debit = Koha::Account::Lines->search({ borrowernumber => $patron->id, accounttype => 'FU' })->next;
2322 is( $manual_debit->amountoutstanding + 0, $manual_debit_amount - $payment_amount, 'reconcile_balance was called' );
2326 subtest '_FixOverduesOnReturn' => sub {
2327 plan tests => 10;
2329 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
2331 my $branchcode = $library2->{branchcode};
2333 my $item = $builder->build_sample_item(
2335 biblionumber => $biblio->biblionumber,
2336 library => $branchcode,
2337 replacementprice => 99.00,
2338 itype => $itemtype,
2342 my $patron = $builder->build( { source => 'Borrower' } );
2344 ## Start with basic call, should just close out the open fine
2345 my $accountline = Koha::Account::Line->new(
2347 borrowernumber => $patron->{borrowernumber},
2348 accounttype => 'FU',
2349 itemnumber => $item->itemnumber,
2350 amount => 99.00,
2351 amountoutstanding => 99.00,
2352 lastincrement => 9.00,
2354 )->store();
2356 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber );
2358 $accountline->_result()->discard_changes();
2360 is( $accountline->amountoutstanding, '99.000000', 'Fine has the same amount outstanding as previously' );
2361 is( $accountline->accounttype, 'F', 'Open fine ( account type FU ) has been closed out ( account type F )');
2364 ## Run again, with exemptfine enabled
2365 $accountline->set(
2367 accounttype => 'FU',
2368 amountoutstanding => 99.00,
2370 )->store();
2372 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1 );
2374 $accountline->_result()->discard_changes();
2375 my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
2377 is( $accountline->amountoutstanding + 0, 0, 'Fine has been reduced to 0' );
2378 is( $accountline->accounttype, 'FFOR', 'Open fine ( account type FU ) has been set to fine forgiven ( account type FFOR )');
2379 is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
2380 is( $offset->amount, '-99.000000', "Amount of offset is correct" );
2382 ## Run again, with dropbox mode enabled
2383 $accountline->set(
2385 accounttype => 'FU',
2386 amountoutstanding => 99.00,
2388 )->store();
2390 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 0, 1 );
2392 $accountline->_result()->discard_changes();
2393 $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Dropbox' })->next();
2395 is( $accountline->amountoutstanding + 0, 90, 'Fine has been reduced to 90' );
2396 is( $accountline->accounttype, 'F', 'Open fine ( account type FU ) has been closed out ( account type F )');
2397 is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via dropbox" );
2398 is( $offset->amount, '-9.000000', "Amount of offset is correct" );
2401 subtest 'Set waiting flag' => sub {
2402 plan tests => 4;
2404 my $library_1 = $builder->build( { source => 'Branch' } );
2405 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2406 my $library_2 = $builder->build( { source => 'Branch' } );
2407 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2409 my $biblio = $builder->build( { source => 'Biblio' } );
2410 my $biblioitem = $builder->build( { source => 'Biblioitem', value => { biblionumber => $biblio->{biblionumber} } } );
2412 my $item = $builder->build(
2414 source => 'Item',
2415 value => {
2416 homebranch => $library_1->{branchcode},
2417 holdingbranch => $library_1->{branchcode},
2418 notforloan => 0,
2419 itemlost => 0,
2420 withdrawn => 0,
2421 biblionumber => $biblioitem->{biblionumber},
2426 set_userenv( $library_2 );
2427 my $reserve_id = AddReserve(
2428 $library_2->{branchcode}, $patron_2->{borrowernumber}, $biblioitem->{biblionumber},
2429 '', 1, undef, undef, '', undef, $item->{itemnumber},
2432 set_userenv( $library_1 );
2433 my $do_transfer = 1;
2434 my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
2435 ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2436 my $hold = Koha::Holds->find( $reserve_id );
2437 is( $hold->found, 'T', 'Hold is in transit' );
2439 my ( $status ) = CheckReserves($item->{itemnumber});
2440 is( $status, 'Reserved', 'Hold is not waiting yet');
2442 set_userenv( $library_2 );
2443 $do_transfer = 0;
2444 AddReturn( $item->{barcode}, $library_2->{branchcode} );
2445 ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2446 $hold = Koha::Holds->find( $reserve_id );
2447 is( $hold->found, 'W', 'Hold is waiting' );
2448 ( $status ) = CheckReserves($item->{itemnumber});
2449 is( $status, 'Waiting', 'Now the hold is waiting');
2452 subtest 'Cancel transfers on lost items' => sub {
2453 plan tests => 5;
2454 my $library_1 = $builder->build( { source => 'Branch' } );
2455 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2456 my $library_2 = $builder->build( { source => 'Branch' } );
2457 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2458 my $biblio = $builder->build( { source => 'Biblio' } );
2459 my $biblioitem = $builder->build( { source => 'Biblioitem', value => { biblionumber => $biblio->{biblionumber} } } );
2460 my $item = $builder->build(
2462 source => 'Item',
2463 value => {
2464 homebranch => $library_1->{branchcode},
2465 holdingbranch => $library_1->{branchcode},
2466 notforloan => 0,
2467 itemlost => 0,
2468 withdrawn => 0,
2469 biblionumber => $biblioitem->{biblionumber},
2474 set_userenv( $library_2 );
2475 my $reserve_id = AddReserve(
2476 $library_2->{branchcode}, $patron_2->{borrowernumber}, $biblioitem->{biblionumber}, '', 1, undef, undef, '', undef, $item->{itemnumber},
2479 #Return book and add transfer
2480 set_userenv( $library_1 );
2481 my $do_transfer = 1;
2482 my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
2483 ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2484 C4::Circulation::transferbook( $library_2->{branchcode}, $item->{barcode} );
2485 my $hold = Koha::Holds->find( $reserve_id );
2486 is( $hold->found, 'T', 'Hold is in transit' );
2488 #Check transfer exists and the items holding branch is the transfer destination branch before marking it as lost
2489 my ($datesent,$frombranch,$tobranch) = GetTransfers($item->{itemnumber});
2490 is( $tobranch, $library_2->{branchcode}, 'The transfer record exists in the branchtransfers table');
2491 my $itemcheck = Koha::Items->find($item->{itemnumber});
2492 is( $itemcheck->holdingbranch, $library_2->{branchcode}, 'Items holding branch is the transfers destination branch before it is marked as lost' );
2494 #Simulate item being marked as lost and confirm the transfer is deleted and the items holding branch is the transfers source branch
2495 ModItem( { itemlost => 1 }, $biblio->{biblionumber}, $item->{itemnumber} );
2496 LostItem( $item->{itemnumber}, 'test', 1 );
2497 ($datesent,$frombranch,$tobranch) = GetTransfers($item->{itemnumber});
2498 is( $tobranch, undef, 'The transfer on the lost item has been deleted as the LostItemCancelOutstandingTransfer is enabled');
2499 $itemcheck = Koha::Items->find($item->{itemnumber});
2500 is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Lost item with cancelled hold has holding branch equallying the transfers source branch' );
2503 subtest 'CanBookBeIssued | is_overdue' => sub {
2504 plan tests => 3;
2506 # Set a simple circ policy
2507 $dbh->do('DELETE FROM issuingrules');
2508 $dbh->do(
2509 q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
2510 issuelength, lengthunit,
2511 renewalsallowed, renewalperiod,
2512 norenewalbefore, auto_renew,
2513 fine, chargeperiod)
2514 VALUES (?, ?, ?, ?,
2515 ?, ?,
2516 ?, ?,
2517 ?, ?,
2518 ?, ?
2522 '*', '*', '*', 25,
2523 14, 'days',
2524 1, 7,
2525 undef, 0,
2526 .10, 1
2529 my $five_days_go = output_pref({ dt => dt_from_string->add( days => 5 ), dateonly => 1});
2530 my $ten_days_go = output_pref({ dt => dt_from_string->add( days => 10), dateonly => 1 });
2531 my $library = $builder->build( { source => 'Branch' } );
2532 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2534 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
2535 my $item = $builder->build(
2537 source => 'Item',
2538 value => {
2539 homebranch => $library->{branchcode},
2540 holdingbranch => $library->{branchcode},
2541 notforloan => 0,
2542 itemlost => 0,
2543 withdrawn => 0,
2544 biblionumber => $biblioitem->{biblionumber},
2549 my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $five_days_go ); # date due was 10d ago
2550 my $actualissue = Koha::Checkouts->find( { itemnumber => $item->{itemnumber} } );
2551 is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
2552 my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->{barcode},$ten_days_go, undef, undef, undef);
2553 is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
2554 is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
2557 subtest 'ItemsDeniedRenewal preference' => sub {
2558 plan tests => 18;
2560 C4::Context->set_preference('ItemsDeniedRenewal','');
2562 my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
2563 $dbh->do(
2565 INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, issuelength, lengthunit, renewalsallowed, renewalperiod,
2566 norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
2569 '*', $idr_lib->branchcode, '*', 25,
2570 14, 'days',
2571 10, 7,
2572 undef, 0,
2573 .10, 1
2576 my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
2577 homebranch => $idr_lib->branchcode,
2578 withdrawn => 1,
2579 itype => 'HIDE',
2580 location => 'PROC',
2581 itemcallnumber => undef,
2582 itemnotes => "",
2585 my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
2586 homebranch => $idr_lib->branchcode,
2587 withdrawn => 0,
2588 itype => 'NOHIDE',
2589 location => 'NOPROC'
2593 my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
2594 branchcode => $idr_lib->branchcode,
2597 my $future = dt_from_string->add( days => 1 );
2598 my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
2599 returndate => undef,
2600 renewals => 0,
2601 auto_renew => 0,
2602 borrowernumber => $idr_borrower->borrowernumber,
2603 itemnumber => $deny_book->itemnumber,
2604 onsite_checkout => 0,
2605 date_due => $future,
2608 my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
2609 returndate => undef,
2610 renewals => 0,
2611 auto_renew => 0,
2612 borrowernumber => $idr_borrower->borrowernumber,
2613 itemnumber => $allow_book->itemnumber,
2614 onsite_checkout => 0,
2615 date_due => $future,
2619 my $idr_rules;
2621 my ( $idr_mayrenew, $idr_error ) =
2622 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2623 is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
2624 is( $idr_error, undef, 'Renewal allowed when no rules' );
2626 $idr_rules="withdrawn: [1]";
2628 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2629 ( $idr_mayrenew, $idr_error ) =
2630 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2631 is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
2632 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
2633 ( $idr_mayrenew, $idr_error ) =
2634 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2635 is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
2636 is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
2638 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
2640 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2641 ( $idr_mayrenew, $idr_error ) =
2642 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2643 is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
2644 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
2645 ( $idr_mayrenew, $idr_error ) =
2646 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2647 is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
2648 is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
2650 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
2652 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2653 ( $idr_mayrenew, $idr_error ) =
2654 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2655 is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
2656 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
2657 ( $idr_mayrenew, $idr_error ) =
2658 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2659 is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
2660 is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
2662 $idr_rules="itemcallnumber: [NULL]";
2663 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2664 ( $idr_mayrenew, $idr_error ) =
2665 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2666 is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
2667 $idr_rules="itemcallnumber: ['']";
2668 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2669 ( $idr_mayrenew, $idr_error ) =
2670 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2671 is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
2673 $idr_rules="itemnotes: [NULL]";
2674 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2675 ( $idr_mayrenew, $idr_error ) =
2676 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2677 is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
2678 $idr_rules="itemnotes: ['']";
2679 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2680 ( $idr_mayrenew, $idr_error ) =
2681 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2682 is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
2685 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
2686 plan tests => 2;
2688 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
2689 my $library = $builder->build( { source => 'Branch' } );
2690 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
2692 my $itemtype = $builder->build(
2694 source => 'Itemtype',
2695 value => { notforloan => undef, }
2699 my $biblioitem = $builder->build( { source => 'Biblioitem', value => { itemtype => $itemtype->{itemtype} } } );
2700 my $item = $builder->build_object(
2702 class => 'Koha::Items',
2703 value => {
2704 homebranch => $library->{branchcode},
2705 holdingbranch => $library->{branchcode},
2706 notforloan => 0,
2707 itemlost => 0,
2708 withdrawn => 0,
2709 biblionumber => $biblioitem->{biblionumber},
2710 biblioitemnumber => $biblioitem->{biblioitemnumber},
2713 )->store;
2715 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2716 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2717 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2720 subtest 'CanBookBeIssued | notforloan' => sub {
2721 plan tests => 2;
2723 t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
2725 my $library = $builder->build( { source => 'Branch' } );
2726 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
2728 my $itemtype = $builder->build(
2730 source => 'Itemtype',
2731 value => { notforloan => undef, }
2735 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
2736 my $item = $builder->build_object(
2738 class => 'Koha::Items',
2739 value => {
2740 homebranch => $library->{branchcode},
2741 holdingbranch => $library->{branchcode},
2742 notforloan => 0,
2743 itemlost => 0,
2744 withdrawn => 0,
2745 itype => $itemtype->{itemtype},
2746 biblionumber => $biblioitem->{biblionumber},
2747 biblioitemnumber => $biblioitem->{biblioitemnumber},
2750 )->store;
2752 my ( $issuingimpossible, $needsconfirmation );
2755 subtest 'item-level_itypes = 1' => sub {
2756 plan tests => 6;
2758 t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
2759 # Is for loan at item type and item level
2760 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2761 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2762 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2764 # not for loan at item type level
2765 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
2766 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2767 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2768 is_deeply(
2769 $issuingimpossible,
2770 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
2771 'Item can not be issued, not for loan at item type level'
2774 # not for loan at item level
2775 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
2776 $item->notforloan( 1 )->store;
2777 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2778 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2779 is_deeply(
2780 $issuingimpossible,
2781 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
2782 'Item can not be issued, not for loan at item type level'
2786 subtest 'item-level_itypes = 0' => sub {
2787 plan tests => 6;
2789 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
2791 # We set another itemtype for biblioitem
2792 my $itemtype = $builder->build(
2794 source => 'Itemtype',
2795 value => { notforloan => undef, }
2799 # for loan at item type and item level
2800 $item->notforloan(0)->store;
2801 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
2802 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2803 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2804 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2806 # not for loan at item type level
2807 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
2808 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2809 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2810 is_deeply(
2811 $issuingimpossible,
2812 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
2813 'Item can not be issued, not for loan at item type level'
2816 # not for loan at item level
2817 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
2818 $item->notforloan( 1 )->store;
2819 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2820 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2821 is_deeply(
2822 $issuingimpossible,
2823 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
2824 'Item can not be issued, not for loan at item type level'
2828 # TODO test with AllowNotForLoanOverride = 1
2831 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
2832 plan tests => 1;
2834 t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
2835 my $item = $builder->build_object({ class => 'Koha::Items', value => { onloan => '2018-01-01' }});
2836 AddReturn( $item->barcode, $item->homebranch );
2837 $item->discard_changes; # refresh
2838 is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
2841 $schema->storage->txn_rollback;
2842 C4::Context->clear_syspref_cache();
2843 $cache->clear_from_cache('single_holidays');
2845 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
2847 plan tests => 13;
2849 $schema->storage->txn_begin;
2851 t::lib::Mocks::mock_preference('item-level_itypes', 1);
2853 my $issuing_charges = 15;
2854 my $title = 'A title';
2855 my $author = 'Author, An';
2856 my $barcode = 'WHATARETHEODDS';
2858 my $circ = Test::MockModule->new('C4::Circulation');
2859 $circ->mock(
2860 'GetIssuingCharges',
2861 sub {
2862 return $issuing_charges;
2866 my $library = $builder->build_object({ class => 'Koha::Libraries' });
2867 my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
2868 my $patron = $builder->build_object({
2869 class => 'Koha::Patrons',
2870 value => { branchcode => $library->id }
2873 my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
2874 my ( undef, undef, $item_id ) = AddItem(
2876 homebranch => $library->id,
2877 holdingbranch => $library->id,
2878 barcode => $barcode,
2879 replacementprice => 23.00,
2880 itype => $itemtype->id
2882 $biblio->biblionumber
2884 my $item = Koha::Items->find( $item_id );
2886 my $context = Test::MockModule->new('C4::Context');
2887 $context->mock( userenv => { branch => $library->id } );
2889 # Check the item out
2890 AddIssue( $patron->unblessed, $item->barcode );
2892 t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
2893 my $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
2894 my $old_log_size = scalar( @{ GetLogs( $date, $date, undef, ["CIRCULATION"], ["RENEWAL"] ) } );
2895 AddRenewal( $patron->id, $item->id, $library->id );
2896 my $new_log_size = scalar( @{ GetLogs( $date, $date, undef, ["CIRCULATION"], ["RENEWAL"] ) } );
2897 is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
2899 my $checkouts = $patron->checkouts;
2900 # The following will fail if run on 00:00:00
2901 unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
2903 t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
2904 $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
2905 $old_log_size = scalar( @{ GetLogs( $date, $date, undef, ["CIRCULATION"], ["RENEWAL"] ) } );
2906 AddRenewal( $patron->id, $item->id, $library->id );
2907 $new_log_size = scalar( @{ GetLogs( $date, $date, undef, ["CIRCULATION"], ["RENEWAL"] ) } );
2908 is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
2910 my $lines = Koha::Account::Lines->search({
2911 borrowernumber => $patron->id,
2912 itemnumber => $item->id
2915 is( $lines->count, 3 );
2917 my $line = $lines->next;
2918 is( $line->accounttype, 'Rent', 'The issuing charge generates an accountline' );
2919 is( $line->branchcode, $library->id, 'AddIssuingCharge correctly sets branchcode' );
2920 is( $line->description, 'Rental', 'AddIssuingCharge set a hardcoded description for the accountline' );
2922 $line = $lines->next;
2923 is( $line->accounttype, 'Rent', 'Fine on renewed item is closed out properly' );
2924 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
2925 is( $line->description, "Renewal of Rental Item $title $barcode", 'AddRenewal set a hardcoded description for the accountline' );
2927 $line = $lines->next;
2928 is( $line->accounttype, 'Rent', 'Fine on renewed item is closed out properly' );
2929 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
2930 is( $line->description, "Renewal of Rental Item $title $barcode", 'AddRenewal set a hardcoded description for the accountline' );
2932 $schema->storage->txn_rollback;
2935 subtest 'ProcessOfflinePayment() tests' => sub {
2937 plan tests => 4;
2939 $schema->storage->txn_begin;
2941 my $amount = 123;
2943 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
2944 my $library = $builder->build_object({ class => 'Koha::Libraries' });
2945 my $result = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
2947 is( $result, 'Success.', 'The right string is returned' );
2949 my $lines = $patron->account->lines;
2950 is( $lines->count, 1, 'line created correctly');
2952 my $line = $lines->next;
2953 is( $line->amount+0, $amount * -1, 'amount picked from params' );
2954 is( $line->branchcode, $library->id, 'branchcode set correctly' );
2956 $schema->storage->txn_rollback;
2961 sub set_userenv {
2962 my ( $library ) = @_;
2963 t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
2966 sub str {
2967 my ( $error, $question, $alert ) = @_;
2968 my $s;
2969 $s = %$error ? ' (error: ' . join( ' ', keys %$error ) . ')' : '';
2970 $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
2971 $s .= %$alert ? ' (alert: ' . join( ' ', keys %$alert ) . ')' : '';
2972 return $s;
2975 sub test_debarment_on_checkout {
2976 my ($params) = @_;
2977 my $item = $params->{item};
2978 my $library = $params->{library};
2979 my $patron = $params->{patron};
2980 my $due_date = $params->{due_date} || dt_from_string;
2981 my $return_date = $params->{return_date} || dt_from_string;
2982 my $expected_expiration_date = $params->{expiration_date};
2984 $expected_expiration_date = output_pref(
2986 dt => $expected_expiration_date,
2987 dateformat => 'sql',
2988 dateonly => 1,
2991 my @caller = caller;
2992 my $line_number = $caller[2];
2993 AddIssue( $patron, $item->{barcode}, $due_date );
2995 my ( undef, $message ) = AddReturn( $item->{barcode}, $library->{branchcode},
2996 undef, undef, $return_date );
2997 is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' )
2998 or diag('AddReturn returned message ' . Dumper $message );
2999 my $debarments = Koha::Patron::Debarments::GetDebarments(
3000 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
3001 is( scalar(@$debarments), 1, 'Test at line ' . $line_number );
3003 is( $debarments->[0]->{expiration},
3004 $expected_expiration_date, 'Test at line ' . $line_number );
3005 Koha::Patron::Debarments::DelUniqueDebarment(
3006 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
3009 subtest 'Incremented fee tests' => sub {
3010 plan tests => 11;
3012 t::lib::Mocks::mock_preference('item-level_itypes', 1);
3014 my $library = $builder->build_object( { class => 'Koha::Libraries' } )->store;
3016 my $module = new Test::MockModule('C4::Context');
3017 $module->mock('userenv', sub { { branch => $library->id } });
3019 my $patron = $builder->build_object(
3021 class => 'Koha::Patrons',
3022 value => { categorycode => $patron_category->{categorycode} }
3024 )->store;
3026 my $itemtype = $builder->build_object(
3028 class => 'Koha::ItemTypes',
3029 value => {
3030 notforloan => undef,
3031 rentalcharge => 0,
3032 rentalcharge_daily => 1.000000
3035 )->store;
3037 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
3038 my $item = $builder->build_object(
3040 class => 'Koha::Items',
3041 value => {
3042 homebranch => $library->id,
3043 holdingbranch => $library->id,
3044 notforloan => 0,
3045 itemlost => 0,
3046 withdrawn => 0,
3047 itype => $itemtype->id,
3048 biblionumber => $biblioitem->{biblionumber},
3049 biblioitemnumber => $biblioitem->{biblioitemnumber},
3052 )->store;
3054 is( $itemtype->rentalcharge_daily, '1.000000', 'Daily rental charge stored and retreived correctly' );
3055 is( $item->effective_itemtype, $itemtype->id, "Itemtype set correctly for item");
3057 my $dt_from = dt_from_string();
3058 my $dt_to = dt_from_string()->add( days => 7 );
3059 my $dt_to_renew = dt_from_string()->add( days => 13 );
3061 t::lib::Mocks::mock_preference('finesCalendar', 'ignoreCalendar');
3062 my $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3063 my $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3064 is( $accountline->amount, '7.000000', "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar" );
3065 $accountline->delete();
3066 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3067 $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3068 is( $accountline->amount, '6.000000', "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar, for renewal" );
3069 $accountline->delete();
3070 $issue->delete();
3072 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
3073 $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3074 $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3075 is( $accountline->amount, '7.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed" );
3076 $accountline->delete();
3077 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3078 $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3079 is( $accountline->amount, '6.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed, for renewal" );
3080 $accountline->delete();
3081 $issue->delete();
3083 my $calendar = C4::Calendar->new( branchcode => $library->id );
3084 $calendar->insert_week_day_holiday(
3085 weekday => 3,
3086 title => 'Test holiday',
3087 description => 'Test holiday'
3089 $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3090 $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3091 is( $accountline->amount, '6.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed Wednesdays" );
3092 $accountline->delete();
3093 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3094 $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3095 is( $accountline->amount, '5.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed Wednesdays, for renewal" );
3096 $accountline->delete();
3097 $issue->delete();
3099 $itemtype->rentalcharge('2.000000')->store;
3100 is( $itemtype->rentalcharge, '2.000000', 'Rental charge updated and retreived correctly' );
3101 $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from);
3102 my $accountlines = Koha::Account::Lines->search({ itemnumber => $item->id });
3103 is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly");
3104 $accountlines->delete();
3105 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3106 $accountlines = Koha::Account::Lines->search({ itemnumber => $item->id });
3107 is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly, for renewal");
3108 $accountlines->delete();
3109 $issue->delete();
3112 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
3113 plan tests => 2;
3115 t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
3116 t::lib::Mocks::mock_preference('item-level_itypes', 1);
3118 my $library =
3119 $builder->build_object( { class => 'Koha::Libraries' } )->store;
3120 my $patron = $builder->build_object(
3122 class => 'Koha::Patrons',
3123 value => { categorycode => $patron_category->{categorycode} }
3125 )->store;
3127 my $itemtype = $builder->build_object(
3129 class => 'Koha::ItemTypes',
3130 value => {
3131 notforloan => 0,
3132 rentalcharge => 0,
3133 rentalcharge_daily => 0
3138 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
3139 my $item = $builder->build_object(
3141 class => 'Koha::Items',
3142 value => {
3143 homebranch => $library->id,
3144 holdingbranch => $library->id,
3145 notforloan => 0,
3146 itemlost => 0,
3147 withdrawn => 0,
3148 itype => $itemtype->id,
3149 biblionumber => $biblioitem->{biblionumber},
3150 biblioitemnumber => $biblioitem->{biblioitemnumber},
3153 )->store;
3155 my ( $issuingimpossible, $needsconfirmation );
3156 my $dt_from = dt_from_string();
3157 my $dt_due = dt_from_string()->add( days => 3 );
3159 $itemtype->rentalcharge('1.000000')->store;
3160 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3161 is_deeply( $needsconfirmation, { RENTALCHARGE => '1' }, 'Item needs rentalcharge confirmation to be issued' );
3162 $itemtype->rentalcharge('0')->store;
3163 $itemtype->rentalcharge_daily('1.000000')->store;
3164 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3165 is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
3166 $itemtype->rentalcharge_daily('0')->store;