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