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