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