Bug 20912: (QA follow-up) Fix for missed signature failure
[koha.git] / t / db_dependent / Circulation.t
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19 use utf8;
20
21 use Test::More tests => 126;
22 use Test::MockModule;
23
24 use Data::Dumper;
25 use DateTime;
26 use Time::Fake;
27 use POSIX qw( floor );
28 use t::lib::Mocks;
29 use t::lib::TestBuilder;
30
31 use C4::Accounts;
32 use C4::Calendar;
33 use C4::Circulation;
34 use C4::Biblio;
35 use C4::Items;
36 use C4::Log;
37 use C4::Reserves;
38 use C4::Overdues qw(UpdateFine CalcFine);
39 use Koha::DateUtils;
40 use Koha::Database;
41 use Koha::IssuingRules;
42 use Koha::Items;
43 use Koha::Checkouts;
44 use Koha::Patrons;
45 use Koha::CirculationRules;
46 use Koha::Subscriptions;
47 use Koha::Account::Lines;
48 use Koha::Account::Offsets;
49 use Koha::ActionLogs;
50
51 my $schema = Koha::Database->schema;
52 $schema->storage->txn_begin;
53 my $builder = t::lib::TestBuilder->new;
54 my $dbh = C4::Context->dbh;
55
56 # Start transaction
57 $dbh->{RaiseError} = 1;
58
59 my $cache = Koha::Caches->get_instance();
60 $dbh->do(q|DELETE FROM special_holidays|);
61 $dbh->do(q|DELETE FROM repeatable_holidays|);
62 $cache->clear_from_cache('single_holidays');
63
64 # Start with a clean slate
65 $dbh->do('DELETE FROM issues');
66 $dbh->do('DELETE FROM borrowers');
67
68 my $library = $builder->build({
69     source => 'Branch',
70 });
71 my $library2 = $builder->build({
72     source => 'Branch',
73 });
74 my $itemtype = $builder->build(
75     {
76         source => 'Itemtype',
77         value  => {
78             notforloan          => undef,
79             rentalcharge        => 0,
80             rentalcharge_daily => 0,
81             defaultreplacecost  => undef,
82             processfee          => undef
83         }
84     }
85 )->{itemtype};
86 my $patron_category = $builder->build(
87     {
88         source => 'Category',
89         value  => {
90             category_type                 => 'P',
91             enrolmentfee                  => 0,
92             BlockExpiredPatronOpacActions => -1, # Pick the pref value
93         }
94     }
95 );
96
97 my $CircControl = C4::Context->preference('CircControl');
98 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
99
100 my $item = {
101     homebranch => $library2->{branchcode},
102     holdingbranch => $library2->{branchcode}
103 };
104
105 my $borrower = {
106     branchcode => $library2->{branchcode}
107 };
108
109 # No userenv, PickupLibrary
110 t::lib::Mocks::mock_preference('IndependentBranches', '0');
111 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
112 is(
113     C4::Context->preference('CircControl'),
114     'PickupLibrary',
115     'CircControl changed to PickupLibrary'
116 );
117 is(
118     C4::Circulation::_GetCircControlBranch($item, $borrower),
119     $item->{$HomeOrHoldingBranch},
120     '_GetCircControlBranch returned item branch (no userenv defined)'
121 );
122
123 # No userenv, PatronLibrary
124 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
125 is(
126     C4::Context->preference('CircControl'),
127     'PatronLibrary',
128     'CircControl changed to PatronLibrary'
129 );
130 is(
131     C4::Circulation::_GetCircControlBranch($item, $borrower),
132     $borrower->{branchcode},
133     '_GetCircControlBranch returned borrower branch'
134 );
135
136 # No userenv, ItemHomeLibrary
137 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
138 is(
139     C4::Context->preference('CircControl'),
140     'ItemHomeLibrary',
141     'CircControl changed to ItemHomeLibrary'
142 );
143 is(
144     $item->{$HomeOrHoldingBranch},
145     C4::Circulation::_GetCircControlBranch($item, $borrower),
146     '_GetCircControlBranch returned item branch'
147 );
148
149 # Now, set a userenv
150 t::lib::Mocks::mock_userenv({ branchcode => $library2->{branchcode} });
151 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
152
153 # Userenv set, PickupLibrary
154 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
155 is(
156     C4::Context->preference('CircControl'),
157     'PickupLibrary',
158     'CircControl changed to PickupLibrary'
159 );
160 is(
161     C4::Circulation::_GetCircControlBranch($item, $borrower),
162     $library2->{branchcode},
163     '_GetCircControlBranch returned current branch'
164 );
165
166 # Userenv set, PatronLibrary
167 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
168 is(
169     C4::Context->preference('CircControl'),
170     'PatronLibrary',
171     'CircControl changed to PatronLibrary'
172 );
173 is(
174     C4::Circulation::_GetCircControlBranch($item, $borrower),
175     $borrower->{branchcode},
176     '_GetCircControlBranch returned borrower branch'
177 );
178
179 # Userenv set, ItemHomeLibrary
180 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
181 is(
182     C4::Context->preference('CircControl'),
183     'ItemHomeLibrary',
184     'CircControl changed to ItemHomeLibrary'
185 );
186 is(
187     C4::Circulation::_GetCircControlBranch($item, $borrower),
188     $item->{$HomeOrHoldingBranch},
189     '_GetCircControlBranch returned item branch'
190 );
191
192 # Reset initial configuration
193 t::lib::Mocks::mock_preference('CircControl', $CircControl);
194 is(
195     C4::Context->preference('CircControl'),
196     $CircControl,
197     'CircControl reset to its initial value'
198 );
199
200 # Set a simple circ policy
201 $dbh->do('DELETE FROM issuingrules');
202 Koha::CirculationRules->search()->delete();
203 $dbh->do(
204     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
205                                 issuelength, lengthunit,
206                                 renewalsallowed, renewalperiod,
207                                 norenewalbefore, auto_renew,
208                                 fine, chargeperiod)
209       VALUES (?, ?, ?, ?,
210               ?, ?,
211               ?, ?,
212               ?, ?,
213               ?, ?
214              )
215     },
216     {},
217     '*', '*', '*', 25,
218     14, 'days',
219     1, 7,
220     undef, 0,
221     .10, 1
222 );
223
224 my ( $reused_itemnumber_1, $reused_itemnumber_2 );
225 {
226 # CanBookBeRenewed tests
227     C4::Context->set_preference('ItemsDeniedRenewal','');
228     # Generate test biblio
229     my $biblio = $builder->build_sample_biblio();
230
231     my $branch = $library2->{branchcode};
232
233     my $item_1 = $builder->build_sample_item(
234         {
235             biblionumber     => $biblio->biblionumber,
236             library          => $branch,
237             replacementprice => 12.00,
238             itype            => $itemtype
239         }
240     );
241     $reused_itemnumber_1 = $item_1->itemnumber;
242
243     my $item_2 = $builder->build_sample_item(
244         {
245             biblionumber     => $biblio->biblionumber,
246             library          => $branch,
247             replacementprice => 23.00,
248             itype            => $itemtype
249         }
250     );
251     $reused_itemnumber_2 = $item_2->itemnumber;
252
253     my $item_3 = $builder->build_sample_item(
254         {
255             biblionumber     => $biblio->biblionumber,
256             library          => $branch,
257             replacementprice => 23.00,
258             itype            => $itemtype
259         }
260     );
261
262     # Create borrowers
263     my %renewing_borrower_data = (
264         firstname =>  'John',
265         surname => 'Renewal',
266         categorycode => $patron_category->{categorycode},
267         branchcode => $branch,
268     );
269
270     my %reserving_borrower_data = (
271         firstname =>  'Katrin',
272         surname => 'Reservation',
273         categorycode => $patron_category->{categorycode},
274         branchcode => $branch,
275     );
276
277     my %hold_waiting_borrower_data = (
278         firstname =>  'Kyle',
279         surname => 'Reservation',
280         categorycode => $patron_category->{categorycode},
281         branchcode => $branch,
282     );
283
284     my %restricted_borrower_data = (
285         firstname =>  'Alice',
286         surname => 'Reservation',
287         categorycode => $patron_category->{categorycode},
288         debarred => '3228-01-01',
289         branchcode => $branch,
290     );
291
292     my %expired_borrower_data = (
293         firstname =>  'Ça',
294         surname => 'Glisse',
295         categorycode => $patron_category->{categorycode},
296         branchcode => $branch,
297         dateexpiry => dt_from_string->subtract( months => 1 ),
298     );
299
300     my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
301     my $reserving_borrowernumber = Koha::Patron->new(\%reserving_borrower_data)->store->borrowernumber;
302     my $hold_waiting_borrowernumber = Koha::Patron->new(\%hold_waiting_borrower_data)->store->borrowernumber;
303     my $restricted_borrowernumber = Koha::Patron->new(\%restricted_borrower_data)->store->borrowernumber;
304     my $expired_borrowernumber = Koha::Patron->new(\%expired_borrower_data)->store->borrowernumber;
305
306     my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
307     my $restricted_borrower = Koha::Patrons->find( $restricted_borrowernumber )->unblessed;
308     my $expired_borrower = Koha::Patrons->find( $expired_borrowernumber )->unblessed;
309
310     my $bibitems       = '';
311     my $priority       = '1';
312     my $resdate        = undef;
313     my $expdate        = undef;
314     my $notes          = '';
315     my $checkitem      = undef;
316     my $found          = undef;
317
318     my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
319     my $datedue = dt_from_string( $issue->date_due() );
320     is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
321
322     my $issue2 = AddIssue( $renewing_borrower, $item_2->barcode);
323     $datedue = dt_from_string( $issue->date_due() );
324     is (defined $issue2, 1, "Item 2 checked out, due date: " . $issue2->date_due());
325
326
327     my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $item_1->itemnumber } )->borrowernumber;
328     is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
329
330     my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
331     is( $renewokay, 1, 'Can renew, no holds for this title or item');
332
333
334     # Biblio-level hold, renewal test
335     AddReserve(
336         $branch, $reserving_borrowernumber, $biblio->biblionumber,
337         $bibitems,  $priority, $resdate, $expdate, $notes,
338         'a title', $checkitem, $found
339     );
340
341     # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
342     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
343     t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
344     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
345     is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
346     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
347     is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
348
349     # Now let's add an item level hold, we should no longer be able to renew the item
350     my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
351         {
352             borrowernumber => $hold_waiting_borrowernumber,
353             biblionumber   => $biblio->biblionumber,
354             itemnumber     => $item_1->itemnumber,
355             branchcode     => $branch,
356             priority       => 3,
357         }
358     );
359     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
360     is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
361     $hold->delete();
362
363     # 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
364     # be able to renew these items
365     $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
366         {
367             borrowernumber => $hold_waiting_borrowernumber,
368             biblionumber   => $biblio->biblionumber,
369             itemnumber     => $item_3->itemnumber,
370             branchcode     => $branch,
371             priority       => 0,
372             found          => 'W'
373         }
374     );
375     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
376     is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
377     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
378     is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
379     t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
380
381     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
382     is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
383     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
384
385     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
386     is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
387     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
388
389     my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
390     my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber )->unblessed;
391     AddIssue($reserving_borrower, $item_3->barcode);
392     my $reserve = $dbh->selectrow_hashref(
393         'SELECT * FROM old_reserves WHERE reserve_id = ?',
394         { Slice => {} },
395         $reserveid
396     );
397     is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
398
399     # Item-level hold, renewal test
400     AddReserve(
401         $branch, $reserving_borrowernumber, $biblio->biblionumber,
402         $bibitems,  $priority, $resdate, $expdate, $notes,
403         'a title', $item_1->itemnumber, $found
404     );
405
406     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
407     is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
408     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
409
410     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber, 1);
411     is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
412
413     # Items can't fill hold for reasons
414     ModItem({ notforloan => 1 }, $biblio->biblionumber, $item_1->itemnumber);
415     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
416     is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
417     ModItem({ notforloan => 0, itype => $itemtype }, $biblio->biblionumber, $item_1->itemnumber);
418
419     # FIXME: Add more for itemtype not for loan etc.
420
421     # Restricted users cannot renew when RestrictionBlockRenewing is enabled
422     my $item_5 = $builder->build_sample_item(
423         {
424             biblionumber     => $biblio->biblionumber,
425             library          => $branch,
426             replacementprice => 23.00,
427             itype            => $itemtype,
428         }
429     );
430     my $datedue5 = AddIssue($restricted_borrower, $item_5->barcode);
431     is (defined $datedue5, 1, "Item with date due checked out, due date: $datedue5");
432
433     t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
434     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
435     is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
436     ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrowernumber, $item_5->itemnumber);
437     is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
438
439     # Users cannot renew an overdue item
440     my $item_6 = $builder->build_sample_item(
441         {
442             biblionumber     => $biblio->biblionumber,
443             library          => $branch,
444             replacementprice => 23.00,
445             itype            => $itemtype,
446         }
447     );
448
449     my $item_7 = $builder->build_sample_item(
450         {
451             biblionumber     => $biblio->biblionumber,
452             library          => $branch,
453             replacementprice => 23.00,
454             itype            => $itemtype,
455         }
456     );
457
458     my $datedue6 = AddIssue( $renewing_borrower, $item_6->barcode);
459     is (defined $datedue6, 1, "Item 2 checked out, due date: ".$datedue6->date_due);
460
461     my $now = dt_from_string();
462     my $five_weeks = DateTime::Duration->new(weeks => 5);
463     my $five_weeks_ago = $now - $five_weeks;
464     t::lib::Mocks::mock_preference('finesMode', 'production');
465
466     my $passeddatedue1 = AddIssue($renewing_borrower, $item_7->barcode, $five_weeks_ago);
467     is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: " . $passeddatedue1->date_due);
468
469     my ( $fine ) = CalcFine( $item_7->unblessed, $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
470     C4::Overdues::UpdateFine(
471         {
472             issue_id       => $passeddatedue1->id(),
473             itemnumber     => $item_7->itemnumber,
474             borrowernumber => $renewing_borrower->{borrowernumber},
475             amount         => $fine,
476             due            => Koha::DateUtils::output_pref($five_weeks_ago)
477         }
478     );
479
480     t::lib::Mocks::mock_preference('RenewalLog', 0);
481     my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
482     my %params_renewal = (
483         timestamp => { -like => $date . "%" },
484         module => "CIRCULATION",
485         action => "RENEWAL",
486     );
487     my %params_issue = (
488         timestamp => { -like => $date . "%" },
489         module => "CIRCULATION",
490         action => "ISSUE"
491     );
492     my $old_log_size = Koha::ActionLogs->count( \%params_renewal );
493     my $dt = dt_from_string();
494     Time::Fake->offset( $dt->epoch );
495     my $datedue1 = AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
496     my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
497     is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
498     isnt (DateTime->compare($datedue1, $dt), 0, "AddRenewal returned a good duedate");
499     Time::Fake->reset;
500
501     t::lib::Mocks::mock_preference('RenewalLog', 1);
502     $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
503     $old_log_size = Koha::ActionLogs->count( \%params_renewal );
504     AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
505     $new_log_size = Koha::ActionLogs->count( \%params_renewal );
506     is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
507
508     my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
509     is( $fines->count, 2 );
510     is( $fines->next->accounttype, 'F', 'Fine on renewed item is closed out properly' );
511     is( $fines->next->accounttype, 'F', 'Fine on renewed item is closed out properly' );
512     $fines->delete();
513
514
515     my $old_issue_log_size = Koha::ActionLogs->count( \%params_issue );
516     my $old_renew_log_size = Koha::ActionLogs->count( \%params_renewal );
517     AddIssue( $renewing_borrower,$item_7->barcode,Koha::DateUtils::output_pref({str=>$datedue6->date_due, dateformat =>'iso'}),0,$date, 0, undef );
518     $new_log_size = Koha::ActionLogs->count( \%params_renewal );
519     is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
520     $new_log_size = Koha::ActionLogs->count( \%params_issue );
521     is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
522
523     $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
524     $fines->delete();
525
526     t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
527     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
528     is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
529     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
530     is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
531
532
533     $hold = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next;
534     $hold->cancel;
535
536     # Bug 14101
537     # Test automatic renewal before value for "norenewalbefore" in policy is set
538     # In this case automatic renewal is not permitted prior to due date
539     my $item_4 = $builder->build_sample_item(
540         {
541             biblionumber     => $biblio->biblionumber,
542             library          => $branch,
543             replacementprice => 16.00,
544             itype            => $itemtype,
545         }
546     );
547
548     $issue = AddIssue( $renewing_borrower, $item_4->barcode, undef, undef, undef, undef, { auto_renew => 1 } );
549     ( $renewokay, $error ) =
550       CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
551     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
552     is( $error, 'auto_too_soon',
553         'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
554
555     # Bug 7413
556     # Test premature manual renewal
557     $dbh->do('UPDATE issuingrules SET norenewalbefore = 7');
558
559     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
560     is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
561     is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
562
563     # Bug 14395
564     # Test 'exact time' setting for syspref NoRenewalBeforePrecision
565     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
566     is(
567         GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
568         $datedue->clone->add( days => -7 ),
569         'Bug 14395: Renewals permitted 7 days before due date, as expected'
570     );
571
572     # Bug 14395
573     # Test 'date' setting for syspref NoRenewalBeforePrecision
574     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
575     is(
576         GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
577         $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
578         'Bug 14395: Renewals permitted 7 days before due date, as expected'
579     );
580
581     # Bug 14101
582     # Test premature automatic renewal
583     ( $renewokay, $error ) =
584       CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
585     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
586     is( $error, 'auto_too_soon',
587         'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
588     );
589
590     # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
591     # and test automatic renewal again
592     $dbh->do('UPDATE issuingrules SET norenewalbefore = 0');
593     ( $renewokay, $error ) =
594       CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
595     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
596     is( $error, 'auto_too_soon',
597         'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
598     );
599
600     # Change policy so that loans can be renewed 99 days prior to the due date
601     # and test automatic renewal again
602     $dbh->do('UPDATE issuingrules SET norenewalbefore = 99');
603     ( $renewokay, $error ) =
604       CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
605     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
606     is( $error, 'auto_renew',
607         'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
608     );
609
610     subtest "too_late_renewal / no_auto_renewal_after" => sub {
611         plan tests => 14;
612         my $item_to_auto_renew = $builder->build(
613             {   source => 'Item',
614                 value  => {
615                     biblionumber  => $biblio->biblionumber,
616                     homebranch    => $branch,
617                     holdingbranch => $branch,
618                 }
619             }
620         );
621
622         my $ten_days_before = dt_from_string->add( days => -10 );
623         my $ten_days_ahead  = dt_from_string->add( days => 10 );
624         AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
625
626         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 9');
627         ( $renewokay, $error ) =
628           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
629         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
630         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
631
632         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 10');
633         ( $renewokay, $error ) =
634           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
635         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
636         is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
637
638         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 11');
639         ( $renewokay, $error ) =
640           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
641         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
642         is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
643
644         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
645         ( $renewokay, $error ) =
646           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
647         is( $renewokay, 0,            'Do not renew, renewal is automatic' );
648         is( $error,     'auto_renew', 'Cannot renew, renew is automatic' );
649
650         $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 ) );
651         ( $renewokay, $error ) =
652           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
653         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
654         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
655
656         $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 ) );
657         ( $renewokay, $error ) =
658           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
659         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
660         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
661
662         $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 ) );
663         ( $renewokay, $error ) =
664           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
665         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
666         is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
667     };
668
669     subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew" => sub {
670         plan tests => 6;
671         my $item_to_auto_renew = $builder->build({
672             source => 'Item',
673             value => {
674                 biblionumber => $biblio->biblionumber,
675                 homebranch       => $branch,
676                 holdingbranch    => $branch,
677             }
678         });
679
680         my $ten_days_before = dt_from_string->add( days => -10 );
681         my $ten_days_ahead = dt_from_string->add( days => 10 );
682         AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
683
684         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
685         C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
686         C4::Context->set_preference('OPACFineNoRenewals','10');
687         my $fines_amount = 5;
688         my $account = Koha::Account->new({patron_id => $renewing_borrowernumber});
689         $account->add_debit(
690             {
691                 amount      => $fines_amount,
692                 interface   => 'test',
693                 type        => 'fine',
694                 item_id     => $item_to_auto_renew->{itemnumber},
695                 description => "Some fines"
696             }
697         )->accounttype('F')->store;
698         ( $renewokay, $error ) =
699           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
700         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
701         is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
702
703         $account->add_debit(
704             {
705                 amount      => $fines_amount,
706                 interface   => 'test',
707                 type        => 'fine',
708                 item_id     => $item_to_auto_renew->{itemnumber},
709                 description => "Some fines"
710             }
711         )->accounttype('F')->store;
712         ( $renewokay, $error ) =
713           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
714         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
715         is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
716
717         $account->add_debit(
718             {
719                 amount      => $fines_amount,
720                 interface   => 'test',
721                 type        => 'fine',
722                 item_id     => $item_to_auto_renew->{itemnumber},
723                 description => "Some fines"
724             }
725         )->accounttype('F')->store;
726         ( $renewokay, $error ) =
727           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
728         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
729         is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
730
731         $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
732     };
733
734     subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
735         plan tests => 6;
736         my $item_to_auto_renew = $builder->build({
737             source => 'Item',
738             value => {
739                 biblionumber => $biblio->biblionumber,
740                 homebranch       => $branch,
741                 holdingbranch    => $branch,
742             }
743         });
744
745         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
746
747         my $ten_days_before = dt_from_string->add( days => -10 );
748         my $ten_days_ahead = dt_from_string->add( days => 10 );
749
750         # Patron is expired and BlockExpiredPatronOpacActions=0
751         # => auto renew is allowed
752         t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
753         my $patron = $expired_borrower;
754         my $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
755         ( $renewokay, $error ) =
756           CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
757         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
758         is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
759         Koha::Checkouts->find( $checkout->issue_id )->delete;
760
761
762         # Patron is expired and BlockExpiredPatronOpacActions=1
763         # => auto renew is not allowed
764         t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
765         $patron = $expired_borrower;
766         $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
767         ( $renewokay, $error ) =
768           CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
769         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
770         is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
771         Koha::Checkouts->find( $checkout->issue_id )->delete;
772
773
774         # Patron is not expired and BlockExpiredPatronOpacActions=1
775         # => auto renew is allowed
776         t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
777         $patron = $renewing_borrower;
778         $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
779         ( $renewokay, $error ) =
780           CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
781         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
782         is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
783         Koha::Checkouts->find( $checkout->issue_id )->delete;
784     };
785
786     subtest "GetLatestAutoRenewDate" => sub {
787         plan tests => 5;
788         my $item_to_auto_renew = $builder->build(
789             {   source => 'Item',
790                 value  => {
791                     biblionumber  => $biblio->biblionumber,
792                     homebranch    => $branch,
793                     holdingbranch => $branch,
794                 }
795             }
796         );
797
798         my $ten_days_before = dt_from_string->add( days => -10 );
799         my $ten_days_ahead  = dt_from_string->add( days => 10 );
800         AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
801         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = NULL, no_auto_renewal_after_hard_limit = NULL');
802         my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
803         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' );
804         my $five_days_before = dt_from_string->add( days => -5 );
805         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 5, no_auto_renewal_after_hard_limit = NULL');
806         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
807         is( $latest_auto_renew_date->truncate( to => 'minute' ),
808             $five_days_before->truncate( to => 'minute' ),
809             'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
810         );
811         my $five_days_ahead = dt_from_string->add( days => 5 );
812         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 15, no_auto_renewal_after_hard_limit = NULL');
813         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
814         is( $latest_auto_renew_date->truncate( to => 'minute' ),
815             $five_days_ahead->truncate( to => 'minute' ),
816             'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
817         );
818         my $two_days_ahead = dt_from_string->add( days => 2 );
819         $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 ) );
820         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
821         is( $latest_auto_renew_date->truncate( to => 'day' ),
822             $two_days_ahead->truncate( to => 'day' ),
823             'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
824         );
825         $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 ) );
826         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
827         is( $latest_auto_renew_date->truncate( to => 'day' ),
828             $two_days_ahead->truncate( to => 'day' ),
829             'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
830         );
831
832     };
833
834     # Too many renewals
835
836     # set policy to forbid renewals
837     $dbh->do('UPDATE issuingrules SET norenewalbefore = NULL, renewalsallowed = 0');
838
839     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
840     is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
841     is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
842
843     # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
844     t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
845     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
846
847     C4::Overdues::UpdateFine(
848         {
849             issue_id       => $issue->id(),
850             itemnumber     => $item_1->itemnumber,
851             borrowernumber => $renewing_borrower->{borrowernumber},
852             amount         => 15.00,
853             type           => q{},
854             due            => Koha::DateUtils::output_pref($datedue)
855         }
856     );
857
858     my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower->{borrowernumber} })->next();
859     is( $line->accounttype, 'FU', 'Account line type is FU' );
860     is( $line->amountoutstanding, '15.000000', 'Account line amount outstanding is 15.00' );
861     is( $line->amount, '15.000000', 'Account line amount is 15.00' );
862     is( $line->issue_id, $issue->id, 'Account line issue id matches' );
863
864     my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
865     is( $offset->type, 'Fine', 'Account offset type is Fine' );
866     is( $offset->amount, '15.000000', 'Account offset amount is 15.00' );
867
868     t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
869     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
870
871     LostItem( $item_1->itemnumber, 'test', 1 );
872
873     $line = Koha::Account::Lines->find($line->id);
874     is( $line->accounttype, 'F', 'Account type correctly changed from FU to F' );
875
876     my $item = Koha::Items->find($item_1->itemnumber);
877     ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
878     my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
879     is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
880
881     my $total_due = $dbh->selectrow_array(
882         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
883         undef, $renewing_borrower->{borrowernumber}
884     );
885
886     is( $total_due, '15.000000', 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
887
888     C4::Context->dbh->do("DELETE FROM accountlines");
889
890     C4::Overdues::UpdateFine(
891         {
892             issue_id       => $issue2->id(),
893             itemnumber     => $item_2->itemnumber,
894             borrowernumber => $renewing_borrower->{borrowernumber},
895             amount         => 15.00,
896             type           => q{},
897             due            => Koha::DateUtils::output_pref($datedue)
898         }
899     );
900
901     LostItem( $item_2->itemnumber, 'test', 0 );
902
903     my $item2 = Koha::Items->find($item_2->itemnumber);
904     ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
905     ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
906
907     $total_due = $dbh->selectrow_array(
908         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
909         undef, $renewing_borrower->{borrowernumber}
910     );
911
912     ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
913
914     my $future = dt_from_string();
915     $future->add( days => 7 );
916     my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
917     ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
918
919     # Users cannot renew any item if there is an overdue item
920     t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
921     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
922     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
923     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
924     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
925
926     my $manager = $builder->build_object({ class => "Koha::Patrons" });
927     t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
928     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
929     $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
930     LostItem( $item_3->itemnumber, 'test', 0 );
931     my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
932     is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
933   }
934
935 {
936     # GetUpcomingDueIssues tests
937     my $branch   = $library2->{branchcode};
938
939     #Create another record
940     my $biblio2 = $builder->build_sample_biblio();
941
942     #Create third item
943     my $item_1 = Koha::Items->find($reused_itemnumber_1);
944     my $item_2 = Koha::Items->find($reused_itemnumber_2);
945     my $item_3 = $builder->build_sample_item(
946         {
947             biblionumber     => $biblio2->biblionumber,
948             library          => $branch,
949             itype            => $itemtype,
950         }
951     );
952
953
954     # Create a borrower
955     my %a_borrower_data = (
956         firstname =>  'Fridolyn',
957         surname => 'SOMERS',
958         categorycode => $patron_category->{categorycode},
959         branchcode => $branch,
960     );
961
962     my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
963     my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
964
965     my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
966     my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
967     my $today = DateTime->today(time_zone => C4::Context->tz());
968
969     my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
970     my $datedue = dt_from_string( $issue->date_due() );
971     my $issue2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
972     my $datedue2 = dt_from_string( $issue->date_due() );
973
974     my $upcoming_dues;
975
976     # GetUpcomingDueIssues tests
977     for my $i(0..1) {
978         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
979         is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
980     }
981
982     #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
983     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
984     is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
985
986     for my $i(3..5) {
987         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
988         is ( scalar( @$upcoming_dues ), 1,
989             "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
990     }
991
992     # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
993
994     my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
995
996     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
997     is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
998
999     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
1000     is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
1001
1002     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
1003     is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
1004
1005     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 }  );
1006     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1007
1008     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1009     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1010
1011     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1012     is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1013
1014 }
1015
1016 {
1017     my $branch   = $library2->{branchcode};
1018
1019     my $biblio = $builder->build_sample_biblio();
1020
1021     #Create third item
1022     my $item = $builder->build_sample_item(
1023         {
1024             biblionumber     => $biblio->biblionumber,
1025             library          => $branch,
1026             itype            => $itemtype,
1027         }
1028     );
1029
1030     # Create a borrower
1031     my %a_borrower_data = (
1032         firstname =>  'Kyle',
1033         surname => 'Hall',
1034         categorycode => $patron_category->{categorycode},
1035         branchcode => $branch,
1036     );
1037
1038     my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1039
1040     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1041     my $issue = AddIssue( $borrower, $item->barcode );
1042     UpdateFine(
1043         {
1044             issue_id       => $issue->id(),
1045             itemnumber     => $item->itemnumber,
1046             borrowernumber => $borrowernumber,
1047             amount         => 0,
1048             type           => q{}
1049         }
1050     );
1051
1052     my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1053     my $count = $hr->{count};
1054
1055     is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1056 }
1057
1058 {
1059     $dbh->do('DELETE FROM issues');
1060     $dbh->do('DELETE FROM items');
1061     $dbh->do('DELETE FROM issuingrules');
1062     Koha::CirculationRules->search()->delete();
1063     $dbh->do(
1064         q{
1065         INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, issuelength, lengthunit, renewalsallowed, renewalperiod,
1066                     norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
1067         },
1068         {},
1069         '*', '*', '*', 25,
1070         14,  'days',
1071         1,   7,
1072         undef,  0,
1073         .10, 1
1074     );
1075     Koha::CirculationRules->set_rules(
1076         {
1077             categorycode => '*',
1078             itemtype     => '*',
1079             branchcode   => '*',
1080             rules        => {
1081                 maxissueqty => 20
1082             }
1083         }
1084     );
1085     my $biblio = $builder->build_sample_biblio();
1086
1087     my $item_1 = $builder->build_sample_item(
1088         {
1089             biblionumber     => $biblio->biblionumber,
1090             library          => $library2->{branchcode},
1091             itype            => $itemtype,
1092         }
1093     );
1094
1095     my $item_2= $builder->build_sample_item(
1096         {
1097             biblionumber     => $biblio->biblionumber,
1098             library          => $library2->{branchcode},
1099             itype            => $itemtype,
1100         }
1101     );
1102
1103     my $borrowernumber1 = Koha::Patron->new({
1104         firstname    => 'Kyle',
1105         surname      => 'Hall',
1106         categorycode => $patron_category->{categorycode},
1107         branchcode   => $library2->{branchcode},
1108     })->store->borrowernumber;
1109     my $borrowernumber2 = Koha::Patron->new({
1110         firstname    => 'Chelsea',
1111         surname      => 'Hall',
1112         categorycode => $patron_category->{categorycode},
1113         branchcode   => $library2->{branchcode},
1114     })->store->borrowernumber;
1115
1116     my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1117     my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1118
1119     my $issue = AddIssue( $borrower1, $item_1->barcode );
1120
1121     my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1122     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1123
1124     AddReserve(
1125         $library2->{branchcode}, $borrowernumber2, $biblio->biblionumber,
1126         '',  1, undef, undef, '',
1127         undef, undef, undef
1128     );
1129
1130     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1131     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1132     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1133     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1134
1135     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1136     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1137     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1138     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1139
1140     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1141     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1142     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1143     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1144
1145     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1146     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1147     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1148     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1149
1150     # Setting item not checked out to be not for loan but holdable
1151     ModItem({ notforloan => -1 }, $biblio->biblionumber, $item_2->itemnumber);
1152
1153     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1154     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' );
1155 }
1156
1157 {
1158     # Don't allow renewing onsite checkout
1159     my $branch   = $library->{branchcode};
1160
1161     #Create another record
1162     my $biblio = $builder->build_sample_biblio();
1163
1164     my $item = $builder->build_sample_item(
1165         {
1166             biblionumber     => $biblio->biblionumber,
1167             library          => $branch,
1168             itype            => $itemtype,
1169         }
1170     );
1171
1172     my $borrowernumber = Koha::Patron->new({
1173         firstname =>  'fn',
1174         surname => 'dn',
1175         categorycode => $patron_category->{categorycode},
1176         branchcode => $branch,
1177     })->store->borrowernumber;
1178
1179     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1180
1181     my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1182     my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $item->itemnumber );
1183     is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1184     is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1185 }
1186
1187 {
1188     my $library = $builder->build({ source => 'Branch' });
1189
1190     my $biblio = $builder->build_sample_biblio();
1191
1192     my $item = $builder->build_sample_item(
1193         {
1194             biblionumber     => $biblio->biblionumber,
1195             library          => $library->{branchcode},
1196             itype            => $itemtype,
1197         }
1198     );
1199
1200     my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1201
1202     my $issue = AddIssue( $patron, $item->barcode );
1203     UpdateFine(
1204         {
1205             issue_id       => $issue->id(),
1206             itemnumber     => $item->itemnumber,
1207             borrowernumber => $patron->{borrowernumber},
1208             amount         => 1,
1209             type           => q{}
1210         }
1211     );
1212     UpdateFine(
1213         {
1214             issue_id       => $issue->id(),
1215             itemnumber     => $item->itemnumber,
1216             borrowernumber => $patron->{borrowernumber},
1217             amount         => 2,
1218             type           => q{}
1219         }
1220     );
1221     is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1222 }
1223
1224 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1225     plan tests => 24;
1226
1227     my $homebranch    = $builder->build( { source => 'Branch' } );
1228     my $holdingbranch = $builder->build( { source => 'Branch' } );
1229     my $otherbranch   = $builder->build( { source => 'Branch' } );
1230     my $patron_1      = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1231     my $patron_2      = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1232
1233     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1234     my $item = $builder->build(
1235         {   source => 'Item',
1236             value  => {
1237                 homebranch    => $homebranch->{branchcode},
1238                 holdingbranch => $holdingbranch->{branchcode},
1239                 biblionumber  => $biblioitem->{biblionumber}
1240             }
1241         }
1242     );
1243
1244     set_userenv($holdingbranch);
1245
1246     my $issue = AddIssue( $patron_1->unblessed, $item->{barcode} );
1247     is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
1248
1249     my ( $error, $question, $alerts );
1250
1251     # AllowReturnToBranch == anywhere
1252     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1253     ## Test that unknown barcodes don't generate internal server errors
1254     set_userenv($homebranch);
1255     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1256     ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1257     ## Can be issued from homebranch
1258     set_userenv($homebranch);
1259     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1260     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1261     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1262     ## Can be issued from holdingbranch
1263     set_userenv($holdingbranch);
1264     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1265     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1266     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1267     ## Can be issued from another branch
1268     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1269     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1270     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1271
1272     # AllowReturnToBranch == holdingbranch
1273     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1274     ## Cannot be issued from homebranch
1275     set_userenv($homebranch);
1276     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1277     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1278     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1279     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
1280     ## Can be issued from holdinbranch
1281     set_userenv($holdingbranch);
1282     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1283     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1284     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1285     ## Cannot be issued from another branch
1286     set_userenv($otherbranch);
1287     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1288     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1289     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1290     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
1291
1292     # AllowReturnToBranch == homebranch
1293     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1294     ## Can be issued from holdinbranch
1295     set_userenv($homebranch);
1296     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1297     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1298     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1299     ## Cannot be issued from holdinbranch
1300     set_userenv($holdingbranch);
1301     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1302     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1303     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1304     is( $error->{branch_to_return},         $homebranch->{branchcode} );
1305     ## Cannot be issued from holdinbranch
1306     set_userenv($otherbranch);
1307     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1308     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1309     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1310     is( $error->{branch_to_return},         $homebranch->{branchcode} );
1311
1312     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1313 };
1314
1315 subtest 'AddIssue & AllowReturnToBranch' => sub {
1316     plan tests => 9;
1317
1318     my $homebranch    = $builder->build( { source => 'Branch' } );
1319     my $holdingbranch = $builder->build( { source => 'Branch' } );
1320     my $otherbranch   = $builder->build( { source => 'Branch' } );
1321     my $patron_1      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1322     my $patron_2      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1323
1324     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1325     my $item = $builder->build(
1326         {   source => 'Item',
1327             value  => {
1328                 homebranch    => $homebranch->{branchcode},
1329                 holdingbranch => $holdingbranch->{branchcode},
1330                 notforloan    => 0,
1331                 itemlost      => 0,
1332                 withdrawn     => 0,
1333                 biblionumber  => $biblioitem->{biblionumber}
1334             }
1335         }
1336     );
1337
1338     set_userenv($holdingbranch);
1339
1340     my $ref_issue = 'Koha::Checkout';
1341     my $issue = AddIssue( $patron_1, $item->{barcode} );
1342
1343     my ( $error, $question, $alerts );
1344
1345     # AllowReturnToBranch == homebranch
1346     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1347     ## Can be issued from homebranch
1348     set_userenv($homebranch);
1349     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1350     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1351     ## Can be issued from holdinbranch
1352     set_userenv($holdingbranch);
1353     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1354     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1355     ## Can be issued from another branch
1356     set_userenv($otherbranch);
1357     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1358     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1359
1360     # AllowReturnToBranch == holdinbranch
1361     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1362     ## Cannot be issued from homebranch
1363     set_userenv($homebranch);
1364     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1365     ## Can be issued from holdingbranch
1366     set_userenv($holdingbranch);
1367     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1368     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1369     ## Cannot be issued from another branch
1370     set_userenv($otherbranch);
1371     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1372
1373     # AllowReturnToBranch == homebranch
1374     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1375     ## Can be issued from homebranch
1376     set_userenv($homebranch);
1377     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1378     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1379     ## Cannot be issued from holdinbranch
1380     set_userenv($holdingbranch);
1381     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1382     ## Cannot be issued from another branch
1383     set_userenv($otherbranch);
1384     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1385     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1386 };
1387
1388 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1389     plan tests => 8;
1390
1391     my $library = $builder->build( { source => 'Branch' } );
1392     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1393
1394     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1395     my $item_1 = $builder->build(
1396         {   source => 'Item',
1397             value  => {
1398                 homebranch    => $library->{branchcode},
1399                 holdingbranch => $library->{branchcode},
1400                 biblionumber  => $biblioitem_1->{biblionumber}
1401             }
1402         }
1403     );
1404     my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1405     my $item_2 = $builder->build(
1406         {   source => 'Item',
1407             value  => {
1408                 homebranch    => $library->{branchcode},
1409                 holdingbranch => $library->{branchcode},
1410                 biblionumber  => $biblioitem_2->{biblionumber}
1411             }
1412         }
1413     );
1414
1415     my ( $error, $question, $alerts );
1416
1417     # Patron cannot issue item_1, they have overdues
1418     my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1419     my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, $yesterday );    # Add an overdue
1420
1421     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1422     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1423     is( keys(%$error) + keys(%$alerts),  0, 'No key for error and alert' . str($error, $question, $alerts) );
1424     is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
1425
1426     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1427     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1428     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1429     is( $error->{USERBLOCKEDOVERDUE},      1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
1430
1431     # Patron cannot issue item_1, they are debarred
1432     my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1433     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
1434     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1435     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1436     is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
1437
1438     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
1439     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1440     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1441     is( $error->{USERBLOCKEDNOENDDATE},    '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
1442 };
1443
1444 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
1445     plan tests => 1;
1446
1447     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1448     my $patron_category_x = $builder->build_object(
1449         {
1450             class => 'Koha::Patron::Categories',
1451             value => { category_type => 'X' }
1452         }
1453     );
1454     my $patron = $builder->build_object(
1455         {
1456             class => 'Koha::Patrons',
1457             value => {
1458                 categorycode  => $patron_category_x->categorycode,
1459                 gonenoaddress => undef,
1460                 lost          => undef,
1461                 debarred      => undef,
1462                 borrowernotes => ""
1463             }
1464         }
1465     );
1466     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1467     my $item_1 = $builder->build(
1468         {
1469             source => 'Item',
1470             value  => {
1471                 homebranch    => $library->branchcode,
1472                 holdingbranch => $library->branchcode,
1473                 biblionumber  => $biblioitem_1->{biblionumber}
1474             }
1475         }
1476     );
1477
1478     my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->{barcode} );
1479     is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
1480
1481     # TODO There are other tests to provide here
1482 };
1483
1484 subtest 'MultipleReserves' => sub {
1485     plan tests => 3;
1486
1487     my $biblio = $builder->build_sample_biblio();
1488
1489     my $branch = $library2->{branchcode};
1490
1491     my $item_1 = $builder->build_sample_item(
1492         {
1493             biblionumber     => $biblio->biblionumber,
1494             library          => $branch,
1495             replacementprice => 12.00,
1496             itype            => $itemtype,
1497         }
1498     );
1499
1500     my $item_2 = $builder->build_sample_item(
1501         {
1502             biblionumber     => $biblio->biblionumber,
1503             library          => $branch,
1504             replacementprice => 12.00,
1505             itype            => $itemtype,
1506         }
1507     );
1508
1509     my $bibitems       = '';
1510     my $priority       = '1';
1511     my $resdate        = undef;
1512     my $expdate        = undef;
1513     my $notes          = '';
1514     my $checkitem      = undef;
1515     my $found          = undef;
1516
1517     my %renewing_borrower_data = (
1518         firstname =>  'John',
1519         surname => 'Renewal',
1520         categorycode => $patron_category->{categorycode},
1521         branchcode => $branch,
1522     );
1523     my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
1524     my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
1525     my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
1526     my $datedue = dt_from_string( $issue->date_due() );
1527     is (defined $issue->date_due(), 1, "item 1 checked out");
1528     my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
1529
1530     my %reserving_borrower_data1 = (
1531         firstname =>  'Katrin',
1532         surname => 'Reservation',
1533         categorycode => $patron_category->{categorycode},
1534         branchcode => $branch,
1535     );
1536     my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
1537     AddReserve(
1538         $branch, $reserving_borrowernumber1, $biblio->biblionumber,
1539         $bibitems,  $priority, $resdate, $expdate, $notes,
1540         'a title', $checkitem, $found
1541     );
1542
1543     my %reserving_borrower_data2 = (
1544         firstname =>  'Kirk',
1545         surname => 'Reservation',
1546         categorycode => $patron_category->{categorycode},
1547         branchcode => $branch,
1548     );
1549     my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
1550     AddReserve(
1551         $branch, $reserving_borrowernumber2, $biblio->biblionumber,
1552         $bibitems,  $priority, $resdate, $expdate, $notes,
1553         'a title', $checkitem, $found
1554     );
1555
1556     {
1557         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1558         is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
1559     }
1560
1561     my $item_3 = $builder->build_sample_item(
1562         {
1563             biblionumber     => $biblio->biblionumber,
1564             library          => $branch,
1565             replacementprice => 12.00,
1566             itype            => $itemtype,
1567         }
1568     );
1569
1570     {
1571         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1572         is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
1573     }
1574 };
1575
1576 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
1577     plan tests => 5;
1578
1579     my $library = $builder->build( { source => 'Branch' } );
1580     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1581
1582     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1583     my $biblionumber = $biblioitem->{biblionumber};
1584     my $item_1 = $builder->build(
1585         {   source => 'Item',
1586             value  => {
1587                 homebranch    => $library->{branchcode},
1588                 holdingbranch => $library->{branchcode},
1589                 biblionumber  => $biblionumber,
1590             }
1591         }
1592     );
1593     my $item_2 = $builder->build(
1594         {   source => 'Item',
1595             value  => {
1596                 homebranch    => $library->{branchcode},
1597                 holdingbranch => $library->{branchcode},
1598                 biblionumber  => $biblionumber,
1599             }
1600         }
1601     );
1602
1603     my ( $error, $question, $alerts );
1604     my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, dt_from_string->add( days => 1 ) );
1605
1606     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1607     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1608     is( keys(%$error) + keys(%$alerts),  0, 'No error or alert should be raised' . str($error, $question, $alerts) );
1609     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) );
1610
1611     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1612     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1613     is( keys(%$error) + keys(%$question) + keys(%$alerts),  0, 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1' . str($error, $question, $alerts) );
1614
1615     # Add a subscription
1616     Koha::Subscription->new({ biblionumber => $biblionumber })->store;
1617
1618     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1619     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1620     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) );
1621
1622     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1623     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1624     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) );
1625 };
1626
1627 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
1628     plan tests => 8;
1629
1630     my $library = $builder->build( { source => 'Branch' } );
1631     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1632
1633     # Add 2 items
1634     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1635     my $item_1 = $builder->build(
1636         {
1637             source => 'Item',
1638             value  => {
1639                 homebranch    => $library->{branchcode},
1640                 holdingbranch => $library->{branchcode},
1641                 notforloan    => 0,
1642                 itemlost      => 0,
1643                 withdrawn     => 0,
1644                 biblionumber  => $biblioitem_1->{biblionumber}
1645             }
1646         }
1647     );
1648     my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1649     my $item_2 = $builder->build(
1650         {
1651             source => 'Item',
1652             value  => {
1653                 homebranch    => $library->{branchcode},
1654                 holdingbranch => $library->{branchcode},
1655                 notforloan    => 0,
1656                 itemlost      => 0,
1657                 withdrawn     => 0,
1658                 biblionumber  => $biblioitem_2->{biblionumber}
1659             }
1660         }
1661     );
1662
1663     # And the issuing rule
1664     Koha::IssuingRules->search->delete;
1665     my $rule = Koha::IssuingRule->new(
1666         {
1667             categorycode => '*',
1668             itemtype     => '*',
1669             branchcode   => '*',
1670             issuelength  => 1,
1671             firstremind  => 1,        # 1 day of grace
1672             finedays     => 2,        # 2 days of fine per day of overdue
1673             lengthunit   => 'days',
1674         }
1675     );
1676     $rule->store();
1677
1678     # Patron cannot issue item_1, they have overdues
1679     my $five_days_ago = dt_from_string->subtract( days => 5 );
1680     my $ten_days_ago  = dt_from_string->subtract( days => 10 );
1681     AddIssue( $patron, $item_1->{barcode}, $five_days_ago );    # Add an overdue
1682     AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1683       ;    # Add another overdue
1684
1685     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
1686     AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, dt_from_string );
1687     my $debarments = Koha::Patron::Debarments::GetDebarments(
1688         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1689     is( scalar(@$debarments), 1 );
1690
1691     # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
1692     # Same for the others
1693     my $expected_expiration = output_pref(
1694         {
1695             dt         => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1696             dateformat => 'sql',
1697             dateonly   => 1
1698         }
1699     );
1700     is( $debarments->[0]->{expiration}, $expected_expiration );
1701
1702     AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, dt_from_string );
1703     $debarments = Koha::Patron::Debarments::GetDebarments(
1704         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1705     is( scalar(@$debarments), 1 );
1706     $expected_expiration = output_pref(
1707         {
1708             dt         => dt_from_string->add( days => ( 10 - 1 ) * 2 ),
1709             dateformat => 'sql',
1710             dateonly   => 1
1711         }
1712     );
1713     is( $debarments->[0]->{expiration}, $expected_expiration );
1714
1715     Koha::Patron::Debarments::DelUniqueDebarment(
1716         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1717
1718     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
1719     AddIssue( $patron, $item_1->{barcode}, $five_days_ago );    # Add an overdue
1720     AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1721       ;    # Add another overdue
1722     AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, dt_from_string );
1723     $debarments = Koha::Patron::Debarments::GetDebarments(
1724         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1725     is( scalar(@$debarments), 1 );
1726     $expected_expiration = output_pref(
1727         {
1728             dt         => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1729             dateformat => 'sql',
1730             dateonly   => 1
1731         }
1732     );
1733     is( $debarments->[0]->{expiration}, $expected_expiration );
1734
1735     AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, dt_from_string );
1736     $debarments = Koha::Patron::Debarments::GetDebarments(
1737         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1738     is( scalar(@$debarments), 1 );
1739     $expected_expiration = output_pref(
1740         {
1741             dt => dt_from_string->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
1742             dateformat => 'sql',
1743             dateonly   => 1
1744         }
1745     );
1746     is( $debarments->[0]->{expiration}, $expected_expiration );
1747 };
1748
1749 subtest 'AddReturn + suspension_chargeperiod' => sub {
1750     plan tests => 21;
1751
1752     my $library = $builder->build( { source => 'Branch' } );
1753     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1754
1755     # Add 2 items
1756     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1757     my $item_1 = $builder->build(
1758         {
1759             source => 'Item',
1760             value  => {
1761                 homebranch    => $library->{branchcode},
1762                 holdingbranch => $library->{branchcode},
1763                 notforloan    => 0,
1764                 itemlost      => 0,
1765                 withdrawn     => 0,
1766                 biblionumber  => $biblioitem_1->{biblionumber}
1767             }
1768         }
1769     );
1770
1771     # And the issuing rule
1772     Koha::IssuingRules->search->delete;
1773     my $rule = Koha::IssuingRule->new(
1774         {
1775             categorycode => '*',
1776             itemtype     => '*',
1777             branchcode   => '*',
1778             issuelength  => 1,
1779             firstremind  => 0,        # 0 day of grace
1780             finedays     => 2,        # 2 days of fine per day of overdue
1781             suspension_chargeperiod => 1,
1782             lengthunit   => 'days',
1783         }
1784     );
1785     $rule->store();
1786
1787     my $five_days_ago = dt_from_string->subtract( days => 5 );
1788     # We want to charge 2 days every day, without grace
1789     # With 5 days of overdue: 5 * Z
1790     my $expected_expiration = dt_from_string->add( days => ( 5 * 2 ) / 1 );
1791     test_debarment_on_checkout(
1792         {
1793             item            => $item_1,
1794             library         => $library,
1795             patron          => $patron,
1796             due_date        => $five_days_ago,
1797             expiration_date => $expected_expiration,
1798         }
1799     );
1800
1801     # We want to charge 2 days every 2 days, without grace
1802     # With 5 days of overdue: (5 * 2) / 2
1803     $rule->suspension_chargeperiod(2)->store;
1804     $expected_expiration = dt_from_string->add( days => floor( 5 * 2 ) / 2 );
1805     test_debarment_on_checkout(
1806         {
1807             item            => $item_1,
1808             library         => $library,
1809             patron          => $patron,
1810             due_date        => $five_days_ago,
1811             expiration_date => $expected_expiration,
1812         }
1813     );
1814
1815     # We want to charge 2 days every 3 days, with 1 day of grace
1816     # With 5 days of overdue: ((5-1) / 3 ) * 2
1817     $rule->suspension_chargeperiod(3)->store;
1818     $rule->firstremind(1)->store;
1819     $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
1820     test_debarment_on_checkout(
1821         {
1822             item            => $item_1,
1823             library         => $library,
1824             patron          => $patron,
1825             due_date        => $five_days_ago,
1826             expiration_date => $expected_expiration,
1827         }
1828     );
1829
1830     # Use finesCalendar to know if holiday must be skipped to calculate the due date
1831     # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
1832     $rule->finedays(2)->store;
1833     $rule->suspension_chargeperiod(1)->store;
1834     $rule->firstremind(0)->store;
1835     t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
1836
1837     # Adding a holiday 2 days ago
1838     my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
1839     my $two_days_ago = dt_from_string->subtract( days => 2 );
1840     $calendar->insert_single_holiday(
1841         day             => $two_days_ago->day,
1842         month           => $two_days_ago->month,
1843         year            => $two_days_ago->year,
1844         title           => 'holidayTest-2d',
1845         description     => 'holidayDesc 2 days ago'
1846     );
1847     # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
1848     $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
1849     test_debarment_on_checkout(
1850         {
1851             item            => $item_1,
1852             library         => $library,
1853             patron          => $patron,
1854             due_date        => $five_days_ago,
1855             expiration_date => $expected_expiration,
1856         }
1857     );
1858
1859     # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
1860     my $two_days_ahead = dt_from_string->add( days => 2 );
1861     $calendar->insert_single_holiday(
1862         day             => $two_days_ahead->day,
1863         month           => $two_days_ahead->month,
1864         year            => $two_days_ahead->year,
1865         title           => 'holidayTest+2d',
1866         description     => 'holidayDesc 2 days ahead'
1867     );
1868
1869     # Same as above, but we should skip D+2
1870     $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
1871     test_debarment_on_checkout(
1872         {
1873             item            => $item_1,
1874             library         => $library,
1875             patron          => $patron,
1876             due_date        => $five_days_ago,
1877             expiration_date => $expected_expiration,
1878         }
1879     );
1880
1881     # Adding another holiday, day of expiration date
1882     my $expected_expiration_dt = dt_from_string($expected_expiration);
1883     $calendar->insert_single_holiday(
1884         day             => $expected_expiration_dt->day,
1885         month           => $expected_expiration_dt->month,
1886         year            => $expected_expiration_dt->year,
1887         title           => 'holidayTest_exp',
1888         description     => 'holidayDesc on expiration date'
1889     );
1890     # Expiration date will be the day after
1891     test_debarment_on_checkout(
1892         {
1893             item            => $item_1,
1894             library         => $library,
1895             patron          => $patron,
1896             due_date        => $five_days_ago,
1897             expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
1898         }
1899     );
1900
1901     test_debarment_on_checkout(
1902         {
1903             item            => $item_1,
1904             library         => $library,
1905             patron          => $patron,
1906             return_date     => dt_from_string->add(days => 5),
1907             expiration_date => dt_from_string->add(days => 5 + (5 * 2 - 1) ),
1908         }
1909     );
1910 };
1911
1912 subtest 'AddReturn | is_overdue' => sub {
1913     plan tests => 5;
1914
1915     t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
1916     t::lib::Mocks::mock_preference('finesMode', 'production');
1917     t::lib::Mocks::mock_preference('MaxFine', '100');
1918
1919     my $library = $builder->build( { source => 'Branch' } );
1920     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1921
1922     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1923     my $item = $builder->build(
1924         {
1925             source => 'Item',
1926             value  => {
1927                 homebranch    => $library->{branchcode},
1928                 holdingbranch => $library->{branchcode},
1929                 notforloan    => 0,
1930                 itemlost      => 0,
1931                 withdrawn     => 0,
1932                 biblionumber  => $biblioitem->{biblionumber},
1933             }
1934         }
1935     );
1936
1937     Koha::IssuingRules->search->delete;
1938     my $rule = Koha::IssuingRule->new(
1939         {
1940             categorycode => '*',
1941             itemtype     => '*',
1942             branchcode   => '*',
1943             issuelength  => 6,
1944             lengthunit   => 'days',
1945             fine         => 1, # Charge 1 every day of overdue
1946             chargeperiod => 1,
1947         }
1948     );
1949     $rule->store();
1950
1951     my $one_day_ago   = dt_from_string->subtract( days => 1 );
1952     my $five_days_ago = dt_from_string->subtract( days => 5 );
1953     my $ten_days_ago  = dt_from_string->subtract( days => 10 );
1954     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1955
1956     # No date specify, today will be used
1957     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1958     AddReturn( $item->{barcode}, $library->{branchcode} );
1959     is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
1960     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1961
1962     # specify return date 5 days before => no overdue
1963     AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
1964     AddReturn( $item->{barcode}, $library->{branchcode}, undef, $ten_days_ago );
1965     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
1966     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1967
1968     # specify return date 5 days later => overdue
1969     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1970     AddReturn( $item->{barcode}, $library->{branchcode}, undef, $five_days_ago );
1971     is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
1972     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1973
1974     # specify dropbox date 5 days before => no overdue
1975     AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
1976     AddReturn( $item->{barcode}, $library->{branchcode}, $ten_days_ago );
1977     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
1978     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1979
1980     # specify dropbox date 5 days later => overdue, or... not
1981     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1982     AddReturn( $item->{barcode}, $library->{branchcode}, $five_days_ago );
1983     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
1984     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1985 };
1986
1987 subtest '_FixAccountForLostAndReturned' => sub {
1988
1989     plan tests => 5;
1990
1991     t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
1992     t::lib::Mocks::mock_preference( 'WhenLostForgiveFine',          0 );
1993
1994     my $processfee_amount  = 20;
1995     my $replacement_amount = 99.00;
1996     my $item_type          = $builder->build_object(
1997         {   class => 'Koha::ItemTypes',
1998             value => {
1999                 notforloan         => undef,
2000                 rentalcharge       => 0,
2001                 defaultreplacecost => undef,
2002                 processfee         => $processfee_amount,
2003                 rentalcharge_daily => 0,
2004             }
2005         }
2006     );
2007     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2008
2009     my $biblio = $builder->build_sample_biblio({ author => 'Hall, Daria' });
2010
2011     subtest 'Full write-off tests' => sub {
2012
2013         plan tests => 10;
2014
2015         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2016         my $manager = $builder->build_object({ class => "Koha::Patrons" });
2017         t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
2018
2019         my $item = $builder->build_sample_item(
2020             {
2021                 biblionumber     => $biblio->biblionumber,
2022                 library          => $library->branchcode,
2023                 replacementprice => $replacement_amount,
2024                 itype            => $item_type->itemtype,
2025             }
2026         );
2027
2028         AddIssue( $patron->unblessed, $item->barcode );
2029
2030         # Simulate item marked as lost
2031         ModItem( { itemlost => 3 }, $biblio->biblionumber, $item->itemnumber );
2032         LostItem( $item->itemnumber, 1 );
2033
2034         my $processing_fee_lines = Koha::Account::Lines->search(
2035             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2036         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2037         my $processing_fee_line = $processing_fee_lines->next;
2038         is( $processing_fee_line->amount + 0,
2039             $processfee_amount, 'The right PF amount is generated' );
2040         is( $processing_fee_line->amountoutstanding + 0,
2041             $processfee_amount, 'The right PF amountoutstanding is generated' );
2042
2043         my $lost_fee_lines = Koha::Account::Lines->search(
2044             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2045         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2046         my $lost_fee_line = $lost_fee_lines->next;
2047         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2048         is( $lost_fee_line->amountoutstanding + 0,
2049             $replacement_amount, 'The right L amountoutstanding is generated' );
2050
2051         my $account = $patron->account;
2052         my $debts   = $account->outstanding_debits;
2053
2054         # Write off the debt
2055         my $credit = $account->add_credit(
2056             {   amount => $account->balance,
2057                 type   => 'writeoff',
2058                 interface => 'test',
2059             }
2060         );
2061         $credit->apply( { debits => $debts, offset_type => 'Writeoff' } );
2062
2063         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2064         is( $credit_return_id, undef, 'No CR account line added' );
2065
2066         $lost_fee_line->discard_changes; # reload from DB
2067         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2068         is( $lost_fee_line->accounttype,
2069             'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2070
2071         is( $patron->account->balance, -0, 'The patron balance is 0, everything was written off' );
2072     };
2073
2074     subtest 'Full payment tests' => sub {
2075
2076         plan tests => 12;
2077
2078         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2079
2080         my $item = $builder->build_sample_item(
2081             {
2082                 biblionumber     => $biblio->biblionumber,
2083                 library          => $library->branchcode,
2084                 replacementprice => $replacement_amount,
2085                 itype            => $item_type->itemtype
2086             }
2087         );
2088
2089         AddIssue( $patron->unblessed, $item->barcode );
2090
2091         # Simulate item marked as lost
2092         ModItem( { itemlost => 1 }, $biblio->biblionumber, $item->itemnumber );
2093         LostItem( $item->itemnumber, 1 );
2094
2095         my $processing_fee_lines = Koha::Account::Lines->search(
2096             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2097         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2098         my $processing_fee_line = $processing_fee_lines->next;
2099         is( $processing_fee_line->amount + 0,
2100             $processfee_amount, 'The right PF amount is generated' );
2101         is( $processing_fee_line->amountoutstanding + 0,
2102             $processfee_amount, 'The right PF amountoutstanding is generated' );
2103
2104         my $lost_fee_lines = Koha::Account::Lines->search(
2105             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2106         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2107         my $lost_fee_line = $lost_fee_lines->next;
2108         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2109         is( $lost_fee_line->amountoutstanding + 0,
2110             $replacement_amount, 'The right L amountountstanding is generated' );
2111
2112         my $account = $patron->account;
2113         my $debts   = $account->outstanding_debits;
2114
2115         # Write off the debt
2116         my $credit = $account->add_credit(
2117             {   amount => $account->balance,
2118                 type   => 'payment',
2119                 interface => 'test',
2120             }
2121         );
2122         $credit->apply( { debits => $debts, offset_type => 'Payment' } );
2123
2124         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2125         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2126
2127         is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2128         is( $credit_return->amount + 0,
2129             -99.00, 'The account line of type CR has an amount of -99' );
2130         is( $credit_return->amountoutstanding + 0,
2131             -99.00, 'The account line of type CR has an amountoutstanding of -99' );
2132
2133         $lost_fee_line->discard_changes;
2134         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2135         is( $lost_fee_line->accounttype,
2136             'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2137
2138         is( $patron->account->balance,
2139             -99, 'The patron balance is -99, a credit that equals the lost fee payment' );
2140     };
2141
2142     subtest 'Test without payment or write off' => sub {
2143
2144         plan tests => 12;
2145
2146         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2147
2148         my $item = $builder->build_sample_item(
2149             {
2150                 biblionumber     => $biblio->biblionumber,
2151                 library          => $library->branchcode,
2152                 replacementprice => 23.00,
2153                 replacementprice => $replacement_amount,
2154                 itype            => $item_type->itemtype
2155             }
2156         );
2157
2158         AddIssue( $patron->unblessed, $item->barcode );
2159
2160         # Simulate item marked as lost
2161         ModItem( { itemlost => 3 }, $biblio->biblionumber, $item->itemnumber );
2162         LostItem( $item->itemnumber, 1 );
2163
2164         my $processing_fee_lines = Koha::Account::Lines->search(
2165             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2166         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2167         my $processing_fee_line = $processing_fee_lines->next;
2168         is( $processing_fee_line->amount + 0,
2169             $processfee_amount, 'The right PF amount is generated' );
2170         is( $processing_fee_line->amountoutstanding + 0,
2171             $processfee_amount, 'The right PF amountoutstanding is generated' );
2172
2173         my $lost_fee_lines = Koha::Account::Lines->search(
2174             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2175         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2176         my $lost_fee_line = $lost_fee_lines->next;
2177         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2178         is( $lost_fee_line->amountoutstanding + 0,
2179             $replacement_amount, 'The right L amountountstanding is generated' );
2180
2181         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2182         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2183
2184         is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2185         is( $credit_return->amount + 0, -99.00, 'The account line of type CR has an amount of -99' );
2186         is( $credit_return->amountoutstanding + 0, 0, 'The account line of type CR has an amountoutstanding of 0' );
2187
2188         $lost_fee_line->discard_changes;
2189         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2190         is( $lost_fee_line->accounttype, 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2191
2192         is( $patron->account->balance, 20, 'The patron balance is 20, still owes the processing fee' );
2193     };
2194
2195     subtest 'Test with partial payement and write off, and remaining debt' => sub {
2196
2197         plan tests => 15;
2198
2199         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2200         my $item = $builder->build_sample_item(
2201             {
2202                 biblionumber     => $biblio->biblionumber,
2203                 library          => $library->branchcode,
2204                 replacementprice => $replacement_amount,
2205                 itype            => $item_type->itemtype
2206             }
2207         );
2208
2209         AddIssue( $patron->unblessed, $item->barcode );
2210
2211         # Simulate item marked as lost
2212         ModItem( { itemlost => 1 }, $biblio->biblionumber, $item->itemnumber );
2213         LostItem( $item->itemnumber, 1 );
2214
2215         my $processing_fee_lines = Koha::Account::Lines->search(
2216             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2217         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2218         my $processing_fee_line = $processing_fee_lines->next;
2219         is( $processing_fee_line->amount + 0,
2220             $processfee_amount, 'The right PF amount is generated' );
2221         is( $processing_fee_line->amountoutstanding + 0,
2222             $processfee_amount, 'The right PF amountoutstanding is generated' );
2223
2224         my $lost_fee_lines = Koha::Account::Lines->search(
2225             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2226         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2227         my $lost_fee_line = $lost_fee_lines->next;
2228         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2229         is( $lost_fee_line->amountoutstanding + 0,
2230             $replacement_amount, 'The right L amountountstanding is generated' );
2231
2232         my $account = $patron->account;
2233         is( $account->balance, $processfee_amount + $replacement_amount, 'Balance is PF + L' );
2234
2235         # Partially pay fee
2236         my $payment_amount = 27;
2237         my $payment        = $account->add_credit(
2238             {   amount => $payment_amount,
2239                 type   => 'payment',
2240                 interface => 'test',
2241             }
2242         );
2243
2244         $payment->apply( { debits => $lost_fee_lines->reset, offset_type => 'Payment' } );
2245
2246         # Partially write off fee
2247         my $write_off_amount = 25;
2248         my $write_off        = $account->add_credit(
2249             {   amount => $write_off_amount,
2250                 type   => 'writeoff',
2251                 interface => 'test',
2252             }
2253         );
2254         $write_off->apply( { debits => $lost_fee_lines->reset, offset_type => 'Writeoff' } );
2255
2256         is( $account->balance,
2257             $processfee_amount + $replacement_amount - $payment_amount - $write_off_amount,
2258             'Payment and write off applied'
2259         );
2260
2261         # Store the amountoutstanding value
2262         $lost_fee_line->discard_changes;
2263         my $outstanding = $lost_fee_line->amountoutstanding;
2264
2265         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2266         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2267
2268         is( $account->balance, $processfee_amount - $payment_amount, 'Balance is PF - payment (CR)' );
2269
2270         $lost_fee_line->discard_changes;
2271         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2272         is( $lost_fee_line->accounttype,
2273             'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2274
2275         is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2276         is( $credit_return->amount + 0,
2277             ($payment_amount + $outstanding ) * -1,
2278             'The account line of type CR has an amount equal to the payment + outstanding'
2279         );
2280         is( $credit_return->amountoutstanding + 0,
2281             $payment_amount * -1,
2282             'The account line of type CR has an amountoutstanding equal to the payment'
2283         );
2284
2285         is( $account->balance,
2286             $processfee_amount - $payment_amount,
2287             'The patron balance is the difference between the PF and the credit'
2288         );
2289     };
2290
2291     subtest 'Partial payement, existing debits and AccountAutoReconcile' => sub {
2292
2293         plan tests => 8;
2294
2295         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2296         my $barcode = 'KD123456793';
2297         my $replacement_amount = 100;
2298         my $processfee_amount  = 20;
2299
2300         my $item_type          = $builder->build_object(
2301             {   class => 'Koha::ItemTypes',
2302                 value => {
2303                     notforloan         => undef,
2304                     rentalcharge       => 0,
2305                     defaultreplacecost => undef,
2306                     processfee         => 0,
2307                     rentalcharge_daily => 0,
2308                 }
2309             }
2310         );
2311         my ( undef, undef, $item_id ) = AddItem(
2312             {   homebranch       => $library->branchcode,
2313                 holdingbranch    => $library->branchcode,
2314                 barcode          => $barcode,
2315                 replacementprice => $replacement_amount,
2316                 itype            => $item_type->itemtype
2317             },
2318             $biblio->biblionumber
2319         );
2320
2321         AddIssue( $patron->unblessed, $barcode );
2322
2323         # Simulate item marked as lost
2324         ModItem( { itemlost => 1 }, $biblio->biblionumber, $item_id );
2325         LostItem( $item_id, 1 );
2326
2327         my $lost_fee_lines = Koha::Account::Lines->search(
2328             { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'L' } );
2329         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2330         my $lost_fee_line = $lost_fee_lines->next;
2331         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2332         is( $lost_fee_line->amountoutstanding + 0,
2333             $replacement_amount, 'The right L amountountstanding is generated' );
2334
2335         my $account = $patron->account;
2336         is( $account->balance, $replacement_amount, 'Balance is L' );
2337
2338         # Partially pay fee
2339         my $payment_amount = 27;
2340         my $payment        = $account->add_credit(
2341             {   amount => $payment_amount,
2342                 type   => 'payment',
2343                 interface => 'test',
2344             }
2345         );
2346         $payment->apply({ debits => $lost_fee_lines->reset, offset_type => 'Payment' });
2347
2348         is( $account->balance,
2349             $replacement_amount - $payment_amount,
2350             'Payment applied'
2351         );
2352
2353         my $manual_debit_amount = 80;
2354         $account->add_debit( { amount => $manual_debit_amount, type => 'fine', interface =>'test' } );
2355
2356         is( $account->balance, $manual_debit_amount + $replacement_amount - $payment_amount, 'Manual debit applied' );
2357
2358         t::lib::Mocks::mock_preference( 'AccountAutoReconcile', 1 );
2359
2360         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item_id, $patron->id );
2361         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2362
2363         is( $account->balance, $manual_debit_amount - $payment_amount, 'Balance is PF - payment (CR)' );
2364
2365         my $manual_debit = Koha::Account::Lines->search({ borrowernumber => $patron->id, accounttype => 'FU' })->next;
2366         is( $manual_debit->amountoutstanding + 0, $manual_debit_amount - $payment_amount, 'reconcile_balance was called' );
2367     };
2368 };
2369
2370 subtest '_FixOverduesOnReturn' => sub {
2371     plan tests => 6;
2372
2373     my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
2374
2375     my $branchcode  = $library2->{branchcode};
2376
2377     my $item = $builder->build_sample_item(
2378         {
2379             biblionumber     => $biblio->biblionumber,
2380             library          => $branchcode,
2381             replacementprice => 99.00,
2382             itype            => $itemtype,
2383         }
2384     );
2385
2386     my $patron = $builder->build( { source => 'Borrower' } );
2387
2388     ## Start with basic call, should just close out the open fine
2389     my $accountline = Koha::Account::Line->new(
2390         {
2391             borrowernumber => $patron->{borrowernumber},
2392             accounttype    => 'FU',
2393             itemnumber     => $item->itemnumber,
2394             amount => 99.00,
2395             amountoutstanding => 99.00,
2396             interface => 'test',
2397         }
2398     )->store();
2399
2400     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber );
2401
2402     $accountline->_result()->discard_changes();
2403
2404     is( $accountline->amountoutstanding, '99.000000', 'Fine has the same amount outstanding as previously' );
2405     is( $accountline->accounttype, 'F', 'Open fine ( account type FU ) has been closed out ( account type F )');
2406
2407
2408     ## Run again, with exemptfine enabled
2409     $accountline->set(
2410         {
2411             accounttype    => 'FU',
2412             amountoutstanding => 99.00,
2413         }
2414     )->store();
2415
2416     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1 );
2417
2418     $accountline->_result()->discard_changes();
2419     my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
2420
2421     is( $accountline->amountoutstanding + 0, 0, 'Fine has been reduced to 0' );
2422     is( $accountline->accounttype, 'FFOR', 'Open fine ( account type FU ) has been set to fine forgiven ( account type FFOR )');
2423     is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
2424     is( $offset->amount, '-99.000000', "Amount of offset is correct" );
2425 };
2426
2427 subtest 'Set waiting flag' => sub {
2428     plan tests => 4;
2429
2430     my $library_1 = $builder->build( { source => 'Branch' } );
2431     my $patron_1  = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2432     my $library_2 = $builder->build( { source => 'Branch' } );
2433     my $patron_2  = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2434
2435     my $biblio = $builder->build( { source => 'Biblio' } );
2436     my $biblioitem = $builder->build( { source => 'Biblioitem', value => { biblionumber => $biblio->{biblionumber} } } );
2437
2438     my $item = $builder->build(
2439         {
2440             source => 'Item',
2441             value  => {
2442                 homebranch    => $library_1->{branchcode},
2443                 holdingbranch => $library_1->{branchcode},
2444                 notforloan    => 0,
2445                 itemlost      => 0,
2446                 withdrawn     => 0,
2447                 biblionumber  => $biblioitem->{biblionumber},
2448             }
2449         }
2450     );
2451
2452     set_userenv( $library_2 );
2453     my $reserve_id = AddReserve(
2454         $library_2->{branchcode}, $patron_2->{borrowernumber}, $biblioitem->{biblionumber},
2455         '', 1, undef, undef, '', undef, $item->{itemnumber},
2456     );
2457
2458     set_userenv( $library_1 );
2459     my $do_transfer = 1;
2460     my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
2461     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2462     my $hold = Koha::Holds->find( $reserve_id );
2463     is( $hold->found, 'T', 'Hold is in transit' );
2464
2465     my ( $status ) = CheckReserves($item->{itemnumber});
2466     is( $status, 'Reserved', 'Hold is not waiting yet');
2467
2468     set_userenv( $library_2 );
2469     $do_transfer = 0;
2470     AddReturn( $item->{barcode}, $library_2->{branchcode} );
2471     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2472     $hold = Koha::Holds->find( $reserve_id );
2473     is( $hold->found, 'W', 'Hold is waiting' );
2474     ( $status ) = CheckReserves($item->{itemnumber});
2475     is( $status, 'Waiting', 'Now the hold is waiting');
2476 };
2477
2478 subtest 'Cancel transfers on lost items' => sub {
2479     plan tests => 5;
2480     my $library_1 = $builder->build( { source => 'Branch' } );
2481     my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2482     my $library_2 = $builder->build( { source => 'Branch' } );
2483     my $patron_2  = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2484     my $biblio = $builder->build( { source => 'Biblio' } );
2485     my $biblioitem = $builder->build( { source => 'Biblioitem', value => { biblionumber => $biblio->{biblionumber} } } );
2486     my $item = $builder->build(
2487         {
2488             source => 'Item',
2489             value => {
2490                 homebranch => $library_1->{branchcode},
2491                 holdingbranch => $library_1->{branchcode},
2492                 notforloan => 0,
2493                 itemlost => 0,
2494                 withdrawn => 0,
2495                 biblionumber => $biblioitem->{biblionumber},
2496             }
2497         }
2498     );
2499
2500     set_userenv( $library_2 );
2501     my $reserve_id = AddReserve(
2502         $library_2->{branchcode}, $patron_2->{borrowernumber}, $biblioitem->{biblionumber}, '', 1, undef, undef, '', undef, $item->{itemnumber},
2503     );
2504
2505     #Return book and add transfer
2506     set_userenv( $library_1 );
2507     my $do_transfer = 1;
2508     my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
2509     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2510     C4::Circulation::transferbook( $library_2->{branchcode}, $item->{barcode} );
2511     my $hold = Koha::Holds->find( $reserve_id );
2512     is( $hold->found, 'T', 'Hold is in transit' );
2513
2514     #Check transfer exists and the items holding branch is the transfer destination branch before marking it as lost
2515     my ($datesent,$frombranch,$tobranch) = GetTransfers($item->{itemnumber});
2516     is( $tobranch, $library_2->{branchcode}, 'The transfer record exists in the branchtransfers table');
2517     my $itemcheck = Koha::Items->find($item->{itemnumber});
2518     is( $itemcheck->holdingbranch, $library_2->{branchcode}, 'Items holding branch is the transfers destination branch before it is marked as lost' );
2519
2520     #Simulate item being marked as lost and confirm the transfer is deleted and the items holding branch is the transfers source branch
2521     ModItem( { itemlost => 1 }, $biblio->{biblionumber}, $item->{itemnumber} );
2522     LostItem( $item->{itemnumber}, 'test', 1 );
2523     ($datesent,$frombranch,$tobranch) = GetTransfers($item->{itemnumber});
2524     is( $tobranch, undef, 'The transfer on the lost item has been deleted as the LostItemCancelOutstandingTransfer is enabled');
2525     $itemcheck = Koha::Items->find($item->{itemnumber});
2526     is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Lost item with cancelled hold has holding branch equallying the transfers source branch' );
2527 };
2528
2529 subtest 'CanBookBeIssued | is_overdue' => sub {
2530     plan tests => 3;
2531
2532     # Set a simple circ policy
2533     $dbh->do('DELETE FROM issuingrules');
2534     $dbh->do(
2535     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
2536                                     issuelength, lengthunit,
2537                                     renewalsallowed, renewalperiod,
2538                                     norenewalbefore, auto_renew,
2539                                     fine, chargeperiod)
2540           VALUES (?, ?, ?, ?,
2541                   ?, ?,
2542                   ?, ?,
2543                   ?, ?,
2544                   ?, ?
2545                  )
2546         },
2547         {},
2548         '*',   '*', '*', 25,
2549         14,  'days',
2550         1,     7,
2551         undef, 0,
2552         .10,   1
2553     );
2554
2555     my $five_days_go = output_pref({ dt => dt_from_string->add( days => 5 ), dateonly => 1});
2556     my $ten_days_go  = output_pref({ dt => dt_from_string->add( days => 10), dateonly => 1 });
2557     my $library = $builder->build( { source => 'Branch' } );
2558     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2559
2560     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
2561     my $item = $builder->build(
2562         {
2563             source => 'Item',
2564             value  => {
2565                 homebranch    => $library->{branchcode},
2566                 holdingbranch => $library->{branchcode},
2567                 notforloan    => 0,
2568                 itemlost      => 0,
2569                 withdrawn     => 0,
2570                 biblionumber  => $biblioitem->{biblionumber},
2571             }
2572         }
2573     );
2574
2575     my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $five_days_go ); # date due was 10d ago
2576     my $actualissue = Koha::Checkouts->find( { itemnumber => $item->{itemnumber} } );
2577     is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
2578     my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->{barcode},$ten_days_go, undef, undef, undef);
2579     is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
2580     is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
2581 };
2582
2583 subtest 'ItemsDeniedRenewal preference' => sub {
2584     plan tests => 18;
2585
2586     C4::Context->set_preference('ItemsDeniedRenewal','');
2587
2588     my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
2589     $dbh->do(
2590         q{
2591         INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, issuelength, lengthunit, renewalsallowed, renewalperiod,
2592                     norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
2593         },
2594         {},
2595         '*', $idr_lib->branchcode, '*', 25,
2596         14,  'days',
2597         10,   7,
2598         undef,  0,
2599         .10, 1
2600     );
2601
2602     my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
2603         homebranch => $idr_lib->branchcode,
2604         withdrawn => 1,
2605         itype => 'HIDE',
2606         location => 'PROC',
2607         itemcallnumber => undef,
2608         itemnotes => "",
2609         }
2610     });
2611     my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
2612         homebranch => $idr_lib->branchcode,
2613         withdrawn => 0,
2614         itype => 'NOHIDE',
2615         location => 'NOPROC'
2616         }
2617     });
2618
2619     my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
2620         branchcode => $idr_lib->branchcode,
2621         }
2622     });
2623     my $future = dt_from_string->add( days => 1 );
2624     my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
2625         returndate => undef,
2626         renewals => 0,
2627         auto_renew => 0,
2628         borrowernumber => $idr_borrower->borrowernumber,
2629         itemnumber => $deny_book->itemnumber,
2630         onsite_checkout => 0,
2631         date_due => $future,
2632         }
2633     });
2634     my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
2635         returndate => undef,
2636         renewals => 0,
2637         auto_renew => 0,
2638         borrowernumber => $idr_borrower->borrowernumber,
2639         itemnumber => $allow_book->itemnumber,
2640         onsite_checkout => 0,
2641         date_due => $future,
2642         }
2643     });
2644
2645     my $idr_rules;
2646
2647     my ( $idr_mayrenew, $idr_error ) =
2648     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2649     is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
2650     is( $idr_error, undef, 'Renewal allowed when no rules' );
2651
2652     $idr_rules="withdrawn: [1]";
2653
2654     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2655     ( $idr_mayrenew, $idr_error ) =
2656     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2657     is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
2658     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
2659     ( $idr_mayrenew, $idr_error ) =
2660     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2661     is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
2662     is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
2663
2664     $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
2665
2666     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2667     ( $idr_mayrenew, $idr_error ) =
2668     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2669     is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
2670     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
2671     ( $idr_mayrenew, $idr_error ) =
2672     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2673     is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
2674     is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
2675
2676     $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
2677
2678     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2679     ( $idr_mayrenew, $idr_error ) =
2680     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2681     is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
2682     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
2683     ( $idr_mayrenew, $idr_error ) =
2684     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2685     is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
2686     is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
2687
2688     $idr_rules="itemcallnumber: [NULL]";
2689     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2690     ( $idr_mayrenew, $idr_error ) =
2691     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2692     is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
2693     $idr_rules="itemcallnumber: ['']";
2694     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2695     ( $idr_mayrenew, $idr_error ) =
2696     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2697     is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
2698
2699     $idr_rules="itemnotes: [NULL]";
2700     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2701     ( $idr_mayrenew, $idr_error ) =
2702     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2703     is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
2704     $idr_rules="itemnotes: ['']";
2705     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2706     ( $idr_mayrenew, $idr_error ) =
2707     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2708     is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
2709 };
2710
2711 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
2712     plan tests => 2;
2713
2714     t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
2715     my $library = $builder->build( { source => 'Branch' } );
2716     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
2717
2718     my $itemtype = $builder->build(
2719         {
2720             source => 'Itemtype',
2721             value  => { notforloan => undef, }
2722         }
2723     );
2724
2725     my $biblioitem = $builder->build( { source => 'Biblioitem', value => { itemtype => $itemtype->{itemtype} } } );
2726     my $item = $builder->build_object(
2727         {
2728             class => 'Koha::Items',
2729             value  => {
2730                 homebranch    => $library->{branchcode},
2731                 holdingbranch => $library->{branchcode},
2732                 notforloan    => 0,
2733                 itemlost      => 0,
2734                 withdrawn     => 0,
2735                 biblionumber  => $biblioitem->{biblionumber},
2736                 biblioitemnumber => $biblioitem->{biblioitemnumber},
2737             }
2738         }
2739     )->store;
2740
2741     my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2742     is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2743     is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2744 };
2745
2746 subtest 'CanBookBeIssued | notforloan' => sub {
2747     plan tests => 2;
2748
2749     t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
2750
2751     my $library = $builder->build( { source => 'Branch' } );
2752     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
2753
2754     my $itemtype = $builder->build(
2755         {
2756             source => 'Itemtype',
2757             value  => { notforloan => undef, }
2758         }
2759     );
2760
2761     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
2762     my $item = $builder->build_object(
2763         {
2764             class => 'Koha::Items',
2765             value  => {
2766                 homebranch    => $library->{branchcode},
2767                 holdingbranch => $library->{branchcode},
2768                 notforloan    => 0,
2769                 itemlost      => 0,
2770                 withdrawn     => 0,
2771                 itype         => $itemtype->{itemtype},
2772                 biblionumber  => $biblioitem->{biblionumber},
2773                 biblioitemnumber => $biblioitem->{biblioitemnumber},
2774             }
2775         }
2776     )->store;
2777
2778     my ( $issuingimpossible, $needsconfirmation );
2779
2780
2781     subtest 'item-level_itypes = 1' => sub {
2782         plan tests => 6;
2783
2784         t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
2785         # Is for loan at item type and item level
2786         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2787         is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2788         is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2789
2790         # not for loan at item type level
2791         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
2792         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2793         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2794         is_deeply(
2795             $issuingimpossible,
2796             { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
2797             'Item can not be issued, not for loan at item type level'
2798         );
2799
2800         # not for loan at item level
2801         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
2802         $item->notforloan( 1 )->store;
2803         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2804         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2805         is_deeply(
2806             $issuingimpossible,
2807             { NOT_FOR_LOAN => 1, item_notforloan => 1 },
2808             'Item can not be issued, not for loan at item type level'
2809         );
2810     };
2811
2812     subtest 'item-level_itypes = 0' => sub {
2813         plan tests => 6;
2814
2815         t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
2816
2817         # We set another itemtype for biblioitem
2818         my $itemtype = $builder->build(
2819             {
2820                 source => 'Itemtype',
2821                 value  => { notforloan => undef, }
2822             }
2823         );
2824
2825         # for loan at item type and item level
2826         $item->notforloan(0)->store;
2827         $item->biblioitem->itemtype($itemtype->{itemtype})->store;
2828         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2829         is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2830         is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2831
2832         # not for loan at item type level
2833         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
2834         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2835         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2836         is_deeply(
2837             $issuingimpossible,
2838             { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
2839             'Item can not be issued, not for loan at item type level'
2840         );
2841
2842         # not for loan at item level
2843         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
2844         $item->notforloan( 1 )->store;
2845         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2846         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2847         is_deeply(
2848             $issuingimpossible,
2849             { NOT_FOR_LOAN => 1, item_notforloan => 1 },
2850             'Item can not be issued, not for loan at item type level'
2851         );
2852     };
2853
2854     # TODO test with AllowNotForLoanOverride = 1
2855 };
2856
2857 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
2858     plan tests => 1;
2859
2860     t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
2861     my $item = $builder->build_object({ class => 'Koha::Items', value  => { onloan => '2018-01-01' }});
2862     AddReturn( $item->barcode, $item->homebranch );
2863     $item->discard_changes; # refresh
2864     is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
2865 };
2866
2867 $schema->storage->txn_rollback;
2868 C4::Context->clear_syspref_cache();
2869 $cache->clear_from_cache('single_holidays');
2870
2871 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
2872
2873     plan tests => 13;
2874
2875     $schema->storage->txn_begin;
2876
2877     t::lib::Mocks::mock_preference('item-level_itypes', 1);
2878
2879     my $issuing_charges = 15;
2880     my $title   = 'A title';
2881     my $author  = 'Author, An';
2882     my $barcode = 'WHATARETHEODDS';
2883
2884     my $circ = Test::MockModule->new('C4::Circulation');
2885     $circ->mock(
2886         'GetIssuingCharges',
2887         sub {
2888             return $issuing_charges;
2889         }
2890     );
2891
2892     my $library  = $builder->build_object({ class => 'Koha::Libraries' });
2893     my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
2894     my $patron   = $builder->build_object({
2895         class => 'Koha::Patrons',
2896         value => { branchcode => $library->id }
2897     });
2898
2899     my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
2900     my ( undef, undef, $item_id ) = AddItem(
2901         {
2902             homebranch       => $library->id,
2903             holdingbranch    => $library->id,
2904             barcode          => $barcode,
2905             replacementprice => 23.00,
2906             itype            => $itemtype->id
2907         },
2908         $biblio->biblionumber
2909     );
2910     my $item = Koha::Items->find( $item_id );
2911
2912     my $context = Test::MockModule->new('C4::Context');
2913     $context->mock( userenv => { branch => $library->id } );
2914
2915     # Check the item out
2916     AddIssue( $patron->unblessed, $item->barcode );
2917     t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
2918     my $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
2919     my %params_renewal = (
2920         timestamp => { -like => $date . "%" },
2921         module => "CIRCULATION",
2922         action => "RENEWAL",
2923     );
2924     my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
2925     AddRenewal( $patron->id, $item->id, $library->id );
2926     my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
2927     is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
2928
2929     my $checkouts = $patron->checkouts;
2930     # The following will fail if run on 00:00:00
2931     unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
2932
2933     t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
2934     $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
2935     $old_log_size = Koha::ActionLogs->count( \%params_renewal );
2936     AddRenewal( $patron->id, $item->id, $library->id );
2937     $new_log_size = Koha::ActionLogs->count( \%params_renewal );
2938     is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
2939
2940     my $lines = Koha::Account::Lines->search({
2941         borrowernumber => $patron->id,
2942         itemnumber     => $item->id
2943     });
2944
2945     is( $lines->count, 3 );
2946
2947     my $line = $lines->next;
2948     is( $line->accounttype, 'Rent',       'The issuing charge generates an accountline' );
2949     is( $line->branchcode,  $library->id, 'AddIssuingCharge correctly sets branchcode' );
2950     is( $line->description, 'Rental',     'AddIssuingCharge set a hardcoded description for the accountline' );
2951
2952     $line = $lines->next;
2953     is( $line->accounttype, 'Rent', 'Fine on renewed item is closed out properly' );
2954     is( $line->branchcode,  $library->id, 'AddRenewal correctly sets branchcode' );
2955     is( $line->description, "Renewal of Rental Item $title $barcode", 'AddRenewal set a hardcoded description for the accountline' );
2956
2957     $line = $lines->next;
2958     is( $line->accounttype, 'Rent', 'Fine on renewed item is closed out properly' );
2959     is( $line->branchcode,  $library->id, 'AddRenewal correctly sets branchcode' );
2960     is( $line->description, "Renewal of Rental Item $title $barcode", 'AddRenewal set a hardcoded description for the accountline' );
2961
2962     $schema->storage->txn_rollback;
2963 };
2964
2965 subtest 'ProcessOfflinePayment() tests' => sub {
2966
2967     plan tests => 4;
2968
2969     $schema->storage->txn_begin;
2970
2971     my $amount = 123;
2972
2973     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
2974     my $library = $builder->build_object({ class => 'Koha::Libraries' });
2975     my $result  = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
2976
2977     is( $result, 'Success.', 'The right string is returned' );
2978
2979     my $lines = $patron->account->lines;
2980     is( $lines->count, 1, 'line created correctly');
2981
2982     my $line = $lines->next;
2983     is( $line->amount+0, $amount * -1, 'amount picked from params' );
2984     is( $line->branchcode, $library->id, 'branchcode set correctly' );
2985
2986     $schema->storage->txn_rollback;
2987 };
2988
2989
2990
2991 sub set_userenv {
2992     my ( $library ) = @_;
2993     t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
2994 }
2995
2996 sub str {
2997     my ( $error, $question, $alert ) = @_;
2998     my $s;
2999     $s  = %$error    ? ' (error: '    . join( ' ', keys %$error    ) . ')' : '';
3000     $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
3001     $s .= %$alert    ? ' (alert: '    . join( ' ', keys %$alert    ) . ')' : '';
3002     return $s;
3003 }
3004
3005 sub test_debarment_on_checkout {
3006     my ($params) = @_;
3007     my $item     = $params->{item};
3008     my $library  = $params->{library};
3009     my $patron   = $params->{patron};
3010     my $due_date = $params->{due_date} || dt_from_string;
3011     my $return_date = $params->{return_date} || dt_from_string;
3012     my $expected_expiration_date = $params->{expiration_date};
3013
3014     $expected_expiration_date = output_pref(
3015         {
3016             dt         => $expected_expiration_date,
3017             dateformat => 'sql',
3018             dateonly   => 1,
3019         }
3020     );
3021     my @caller      = caller;
3022     my $line_number = $caller[2];
3023     AddIssue( $patron, $item->{barcode}, $due_date );
3024
3025     my ( undef, $message ) = AddReturn( $item->{barcode}, $library->{branchcode}, undef, $return_date );
3026     is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' )
3027         or diag('AddReturn returned message ' . Dumper $message );
3028     my $debarments = Koha::Patron::Debarments::GetDebarments(
3029         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
3030     is( scalar(@$debarments), 1, 'Test at line ' . $line_number );
3031
3032     is( $debarments->[0]->{expiration},
3033         $expected_expiration_date, 'Test at line ' . $line_number );
3034     Koha::Patron::Debarments::DelUniqueDebarment(
3035         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
3036 };
3037
3038 subtest 'Incremented fee tests' => sub {
3039     plan tests => 11;
3040
3041     t::lib::Mocks::mock_preference('item-level_itypes', 1);
3042
3043     my $library = $builder->build_object( { class => 'Koha::Libraries' } )->store;
3044
3045     my $module = new Test::MockModule('C4::Context');
3046     $module->mock('userenv', sub { { branch => $library->id } });
3047
3048     my $patron = $builder->build_object(
3049         {
3050             class => 'Koha::Patrons',
3051             value => { categorycode => $patron_category->{categorycode} }
3052         }
3053     )->store;
3054
3055     my $itemtype = $builder->build_object(
3056         {
3057             class => 'Koha::ItemTypes',
3058             value  => {
3059                 notforloan          => undef,
3060                 rentalcharge        => 0,
3061                 rentalcharge_daily => 1.000000
3062             }
3063         }
3064     )->store;
3065
3066     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
3067     my $item = $builder->build_object(
3068         {
3069             class => 'Koha::Items',
3070             value => {
3071                 homebranch       => $library->id,
3072                 holdingbranch    => $library->id,
3073                 notforloan       => 0,
3074                 itemlost         => 0,
3075                 withdrawn        => 0,
3076                 itype            => $itemtype->id,
3077                 biblionumber     => $biblioitem->{biblionumber},
3078                 biblioitemnumber => $biblioitem->{biblioitemnumber},
3079             }
3080         }
3081     )->store;
3082
3083     is( $itemtype->rentalcharge_daily, '1.000000', 'Daily rental charge stored and retreived correctly' );
3084     is( $item->effective_itemtype, $itemtype->id, "Itemtype set correctly for item");
3085
3086     my $dt_from = dt_from_string();
3087     my $dt_to = dt_from_string()->add( days => 7 );
3088     my $dt_to_renew = dt_from_string()->add( days => 13 );
3089
3090     t::lib::Mocks::mock_preference('finesCalendar', 'ignoreCalendar');
3091     my $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3092     my $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3093     is( $accountline->amount, '7.000000', "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar" );
3094     $accountline->delete();
3095     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3096     $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3097     is( $accountline->amount, '6.000000', "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar, for renewal" );
3098     $accountline->delete();
3099     $issue->delete();
3100
3101     t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
3102     $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3103     $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3104     is( $accountline->amount, '7.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed" );
3105     $accountline->delete();
3106     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3107     $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3108     is( $accountline->amount, '6.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed, for renewal" );
3109     $accountline->delete();
3110     $issue->delete();
3111
3112     my $calendar = C4::Calendar->new( branchcode => $library->id );
3113     $calendar->insert_week_day_holiday(
3114         weekday     => 3,
3115         title       => 'Test holiday',
3116         description => 'Test holiday'
3117     );
3118     $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3119     $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3120     is( $accountline->amount, '6.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed Wednesdays" );
3121     $accountline->delete();
3122     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3123     $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3124     is( $accountline->amount, '5.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed Wednesdays, for renewal" );
3125     $accountline->delete();
3126     $issue->delete();
3127
3128     $itemtype->rentalcharge('2.000000')->store;
3129     is( $itemtype->rentalcharge, '2.000000', 'Rental charge updated and retreived correctly' );
3130     $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from);
3131     my $accountlines = Koha::Account::Lines->search({ itemnumber => $item->id });
3132     is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly");
3133     $accountlines->delete();
3134     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3135     $accountlines = Koha::Account::Lines->search({ itemnumber => $item->id });
3136     is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly, for renewal");
3137     $accountlines->delete();
3138     $issue->delete();
3139 };
3140
3141 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
3142     plan tests => 2;
3143
3144     t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
3145     t::lib::Mocks::mock_preference('item-level_itypes', 1);
3146
3147     my $library =
3148       $builder->build_object( { class => 'Koha::Libraries' } )->store;
3149     my $patron = $builder->build_object(
3150         {
3151             class => 'Koha::Patrons',
3152             value => { categorycode => $patron_category->{categorycode} }
3153         }
3154     )->store;
3155
3156     my $itemtype = $builder->build_object(
3157         {
3158             class => 'Koha::ItemTypes',
3159             value => {
3160                 notforloan             => 0,
3161                 rentalcharge           => 0,
3162                 rentalcharge_daily => 0
3163             }
3164         }
3165     );
3166
3167     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
3168     my $item = $builder->build_object(
3169         {
3170             class => 'Koha::Items',
3171             value  => {
3172                 homebranch    => $library->id,
3173                 holdingbranch => $library->id,
3174                 notforloan    => 0,
3175                 itemlost      => 0,
3176                 withdrawn     => 0,
3177                 itype         => $itemtype->id,
3178                 biblionumber  => $biblioitem->{biblionumber},
3179                 biblioitemnumber => $biblioitem->{biblioitemnumber},
3180             }
3181         }
3182     )->store;
3183
3184     my ( $issuingimpossible, $needsconfirmation );
3185     my $dt_from = dt_from_string();
3186     my $dt_due = dt_from_string()->add( days => 3 );
3187
3188     $itemtype->rentalcharge('1.000000')->store;
3189     ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3190     is_deeply( $needsconfirmation, { RENTALCHARGE => '1' }, 'Item needs rentalcharge confirmation to be issued' );
3191     $itemtype->rentalcharge('0')->store;
3192     $itemtype->rentalcharge_daily('1.000000')->store;
3193     ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3194     is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
3195     $itemtype->rentalcharge_daily('0')->store;
3196 };