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