Bug 22917: Prevent Circulation.t if tests ran too slowly
[koha.git] / t / db_dependent / Circulation.t
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19 use utf8;
20
21 use Test::More tests => 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 = $builder->build(
2001         {
2002             source => 'Item',
2003             value  => {
2004                 homebranch    => $library->{branchcode},
2005                 holdingbranch => $library->{branchcode},
2006                 notforloan    => 0,
2007                 itemlost      => 0,
2008                 withdrawn     => 0,
2009                 biblionumber  => $biblioitem->{biblionumber},
2010             }
2011         }
2012     );
2013
2014     Koha::IssuingRules->search->delete;
2015     my $rule = Koha::IssuingRule->new(
2016         {
2017             categorycode => '*',
2018             itemtype     => '*',
2019             branchcode   => '*',
2020             issuelength  => 6,
2021             lengthunit   => 'days',
2022             fine         => 1, # Charge 1 every day of overdue
2023             chargeperiod => 1,
2024         }
2025     );
2026     $rule->store();
2027
2028     my $one_day_ago   = dt_from_string->subtract( days => 1 );
2029     my $five_days_ago = dt_from_string->subtract( days => 5 );
2030     my $ten_days_ago  = dt_from_string->subtract( days => 10 );
2031     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
2032
2033     # No date specify, today will be used
2034     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2035     AddReturn( $item->{barcode}, $library->{branchcode} );
2036     is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
2037     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2038
2039     # specify return date 5 days before => no overdue
2040     AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
2041     AddReturn( $item->{barcode}, $library->{branchcode}, undef, $ten_days_ago );
2042     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2043     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2044
2045     # specify return date 5 days later => overdue
2046     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2047     AddReturn( $item->{barcode}, $library->{branchcode}, undef, $five_days_ago );
2048     is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
2049     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2050
2051     # specify dropbox date 5 days before => no overdue
2052     AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
2053     AddReturn( $item->{barcode}, $library->{branchcode}, $ten_days_ago );
2054     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2055     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2056
2057     # specify dropbox date 5 days later => overdue, or... not
2058     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2059     AddReturn( $item->{barcode}, $library->{branchcode}, $five_days_ago );
2060     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue in dropbox mode' ); # FIXME? This is weird, the OVERDUE fine is created ( _CalculateAndUpdateFine > C4::Overdues::UpdateFine ) then remove later (in _FixOverduesOnReturn). Looks like it is a feature
2061     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2062 };
2063
2064 subtest '_FixAccountForLostAndReturned' => sub {
2065
2066     plan tests => 5;
2067
2068     t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
2069     t::lib::Mocks::mock_preference( 'WhenLostForgiveFine',          0 );
2070
2071     my $processfee_amount  = 20;
2072     my $replacement_amount = 99.00;
2073     my $item_type          = $builder->build_object(
2074         {   class => 'Koha::ItemTypes',
2075             value => {
2076                 notforloan         => undef,
2077                 rentalcharge       => 0,
2078                 defaultreplacecost => undef,
2079                 processfee         => $processfee_amount,
2080                 rentalcharge_daily => 0,
2081             }
2082         }
2083     );
2084     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2085
2086     my $biblio = $builder->build_sample_biblio({ author => 'Hall, Daria' });
2087
2088     subtest 'Full write-off tests' => sub {
2089
2090         plan tests => 10;
2091
2092         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2093         my $manager = $builder->build_object({ class => "Koha::Patrons" });
2094         t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
2095
2096         my $item = $builder->build_sample_item(
2097             {
2098                 biblionumber     => $biblio->biblionumber,
2099                 library          => $library->branchcode,
2100                 replacementprice => $replacement_amount,
2101                 itype            => $item_type->itemtype,
2102             }
2103         );
2104
2105         AddIssue( $patron->unblessed, $item->barcode );
2106
2107         # Simulate item marked as lost
2108         ModItem( { itemlost => 3 }, $biblio->biblionumber, $item->itemnumber );
2109         LostItem( $item->itemnumber, 1 );
2110
2111         my $processing_fee_lines = Koha::Account::Lines->search(
2112             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2113         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2114         my $processing_fee_line = $processing_fee_lines->next;
2115         is( $processing_fee_line->amount + 0,
2116             $processfee_amount, 'The right PF amount is generated' );
2117         is( $processing_fee_line->amountoutstanding + 0,
2118             $processfee_amount, 'The right PF amountoutstanding is generated' );
2119
2120         my $lost_fee_lines = Koha::Account::Lines->search(
2121             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2122         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2123         my $lost_fee_line = $lost_fee_lines->next;
2124         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2125         is( $lost_fee_line->amountoutstanding + 0,
2126             $replacement_amount, 'The right L amountoutstanding is generated' );
2127
2128         my $account = $patron->account;
2129         my $debts   = $account->outstanding_debits;
2130
2131         # Write off the debt
2132         my $credit = $account->add_credit(
2133             {   amount => $account->balance,
2134                 type   => 'writeoff',
2135                 interface => 'test',
2136             }
2137         );
2138         $credit->apply( { debits => $debts, offset_type => 'Writeoff' } );
2139
2140         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2141         is( $credit_return_id, undef, 'No CR account line added' );
2142
2143         $lost_fee_line->discard_changes; # reload from DB
2144         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2145         is( $lost_fee_line->accounttype,
2146             'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2147
2148         is( $patron->account->balance, -0, 'The patron balance is 0, everything was written off' );
2149     };
2150
2151     subtest 'Full payment tests' => sub {
2152
2153         plan tests => 12;
2154
2155         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2156
2157         my $item = $builder->build_sample_item(
2158             {
2159                 biblionumber     => $biblio->biblionumber,
2160                 library          => $library->branchcode,
2161                 replacementprice => $replacement_amount,
2162                 itype            => $item_type->itemtype
2163             }
2164         );
2165
2166         AddIssue( $patron->unblessed, $item->barcode );
2167
2168         # Simulate item marked as lost
2169         ModItem( { itemlost => 1 }, $biblio->biblionumber, $item->itemnumber );
2170         LostItem( $item->itemnumber, 1 );
2171
2172         my $processing_fee_lines = Koha::Account::Lines->search(
2173             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2174         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2175         my $processing_fee_line = $processing_fee_lines->next;
2176         is( $processing_fee_line->amount + 0,
2177             $processfee_amount, 'The right PF amount is generated' );
2178         is( $processing_fee_line->amountoutstanding + 0,
2179             $processfee_amount, 'The right PF amountoutstanding is generated' );
2180
2181         my $lost_fee_lines = Koha::Account::Lines->search(
2182             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2183         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2184         my $lost_fee_line = $lost_fee_lines->next;
2185         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2186         is( $lost_fee_line->amountoutstanding + 0,
2187             $replacement_amount, 'The right L amountountstanding is generated' );
2188
2189         my $account = $patron->account;
2190         my $debts   = $account->outstanding_debits;
2191
2192         # Write off the debt
2193         my $credit = $account->add_credit(
2194             {   amount => $account->balance,
2195                 type   => 'payment',
2196                 interface => 'test',
2197             }
2198         );
2199         $credit->apply( { debits => $debts, offset_type => 'Payment' } );
2200
2201         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2202         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2203
2204         is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2205         is( $credit_return->amount + 0,
2206             -99.00, 'The account line of type CR has an amount of -99' );
2207         is( $credit_return->amountoutstanding + 0,
2208             -99.00, 'The account line of type CR has an amountoutstanding of -99' );
2209
2210         $lost_fee_line->discard_changes;
2211         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2212         is( $lost_fee_line->accounttype,
2213             'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2214
2215         is( $patron->account->balance,
2216             -99, 'The patron balance is -99, a credit that equals the lost fee payment' );
2217     };
2218
2219     subtest 'Test without payment or write off' => sub {
2220
2221         plan tests => 12;
2222
2223         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2224
2225         my $item = $builder->build_sample_item(
2226             {
2227                 biblionumber     => $biblio->biblionumber,
2228                 library          => $library->branchcode,
2229                 replacementprice => 23.00,
2230                 replacementprice => $replacement_amount,
2231                 itype            => $item_type->itemtype
2232             }
2233         );
2234
2235         AddIssue( $patron->unblessed, $item->barcode );
2236
2237         # Simulate item marked as lost
2238         ModItem( { itemlost => 3 }, $biblio->biblionumber, $item->itemnumber );
2239         LostItem( $item->itemnumber, 1 );
2240
2241         my $processing_fee_lines = Koha::Account::Lines->search(
2242             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2243         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2244         my $processing_fee_line = $processing_fee_lines->next;
2245         is( $processing_fee_line->amount + 0,
2246             $processfee_amount, 'The right PF amount is generated' );
2247         is( $processing_fee_line->amountoutstanding + 0,
2248             $processfee_amount, 'The right PF amountoutstanding is generated' );
2249
2250         my $lost_fee_lines = Koha::Account::Lines->search(
2251             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2252         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2253         my $lost_fee_line = $lost_fee_lines->next;
2254         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2255         is( $lost_fee_line->amountoutstanding + 0,
2256             $replacement_amount, 'The right L amountountstanding is generated' );
2257
2258         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2259         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2260
2261         is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2262         is( $credit_return->amount + 0, -99.00, 'The account line of type CR has an amount of -99' );
2263         is( $credit_return->amountoutstanding + 0, 0, 'The account line of type CR has an amountoutstanding of 0' );
2264
2265         $lost_fee_line->discard_changes;
2266         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2267         is( $lost_fee_line->accounttype, 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2268
2269         is( $patron->account->balance, 20, 'The patron balance is 20, still owes the processing fee' );
2270     };
2271
2272     subtest 'Test with partial payement and write off, and remaining debt' => sub {
2273
2274         plan tests => 15;
2275
2276         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2277         my $item = $builder->build_sample_item(
2278             {
2279                 biblionumber     => $biblio->biblionumber,
2280                 library          => $library->branchcode,
2281                 replacementprice => $replacement_amount,
2282                 itype            => $item_type->itemtype
2283             }
2284         );
2285
2286         AddIssue( $patron->unblessed, $item->barcode );
2287
2288         # Simulate item marked as lost
2289         ModItem( { itemlost => 1 }, $biblio->biblionumber, $item->itemnumber );
2290         LostItem( $item->itemnumber, 1 );
2291
2292         my $processing_fee_lines = Koha::Account::Lines->search(
2293             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2294         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2295         my $processing_fee_line = $processing_fee_lines->next;
2296         is( $processing_fee_line->amount + 0,
2297             $processfee_amount, 'The right PF amount is generated' );
2298         is( $processing_fee_line->amountoutstanding + 0,
2299             $processfee_amount, 'The right PF amountoutstanding is generated' );
2300
2301         my $lost_fee_lines = Koha::Account::Lines->search(
2302             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2303         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2304         my $lost_fee_line = $lost_fee_lines->next;
2305         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2306         is( $lost_fee_line->amountoutstanding + 0,
2307             $replacement_amount, 'The right L amountountstanding is generated' );
2308
2309         my $account = $patron->account;
2310         is( $account->balance, $processfee_amount + $replacement_amount, 'Balance is PF + L' );
2311
2312         # Partially pay fee
2313         my $payment_amount = 27;
2314         my $payment        = $account->add_credit(
2315             {   amount => $payment_amount,
2316                 type   => 'payment',
2317                 interface => 'test',
2318             }
2319         );
2320
2321         $payment->apply( { debits => $lost_fee_lines->reset, offset_type => 'Payment' } );
2322
2323         # Partially write off fee
2324         my $write_off_amount = 25;
2325         my $write_off        = $account->add_credit(
2326             {   amount => $write_off_amount,
2327                 type   => 'writeoff',
2328                 interface => 'test',
2329             }
2330         );
2331         $write_off->apply( { debits => $lost_fee_lines->reset, offset_type => 'Writeoff' } );
2332
2333         is( $account->balance,
2334             $processfee_amount + $replacement_amount - $payment_amount - $write_off_amount,
2335             'Payment and write off applied'
2336         );
2337
2338         # Store the amountoutstanding value
2339         $lost_fee_line->discard_changes;
2340         my $outstanding = $lost_fee_line->amountoutstanding;
2341
2342         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2343         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2344
2345         is( $account->balance, $processfee_amount - $payment_amount, 'Balance is PF - payment (CR)' );
2346
2347         $lost_fee_line->discard_changes;
2348         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2349         is( $lost_fee_line->accounttype,
2350             'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2351
2352         is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2353         is( $credit_return->amount + 0,
2354             ($payment_amount + $outstanding ) * -1,
2355             'The account line of type CR has an amount equal to the payment + outstanding'
2356         );
2357         is( $credit_return->amountoutstanding + 0,
2358             $payment_amount * -1,
2359             'The account line of type CR has an amountoutstanding equal to the payment'
2360         );
2361
2362         is( $account->balance,
2363             $processfee_amount - $payment_amount,
2364             'The patron balance is the difference between the PF and the credit'
2365         );
2366     };
2367
2368     subtest 'Partial payement, existing debits and AccountAutoReconcile' => sub {
2369
2370         plan tests => 8;
2371
2372         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2373         my $barcode = 'KD123456793';
2374         my $replacement_amount = 100;
2375         my $processfee_amount  = 20;
2376
2377         my $item_type          = $builder->build_object(
2378             {   class => 'Koha::ItemTypes',
2379                 value => {
2380                     notforloan         => undef,
2381                     rentalcharge       => 0,
2382                     defaultreplacecost => undef,
2383                     processfee         => 0,
2384                     rentalcharge_daily => 0,
2385                 }
2386             }
2387         );
2388         my ( undef, undef, $item_id ) = AddItem(
2389             {   homebranch       => $library->branchcode,
2390                 holdingbranch    => $library->branchcode,
2391                 barcode          => $barcode,
2392                 replacementprice => $replacement_amount,
2393                 itype            => $item_type->itemtype
2394             },
2395             $biblio->biblionumber
2396         );
2397
2398         AddIssue( $patron->unblessed, $barcode );
2399
2400         # Simulate item marked as lost
2401         ModItem( { itemlost => 1 }, $biblio->biblionumber, $item_id );
2402         LostItem( $item_id, 1 );
2403
2404         my $lost_fee_lines = Koha::Account::Lines->search(
2405             { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'L' } );
2406         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2407         my $lost_fee_line = $lost_fee_lines->next;
2408         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2409         is( $lost_fee_line->amountoutstanding + 0,
2410             $replacement_amount, 'The right L amountountstanding is generated' );
2411
2412         my $account = $patron->account;
2413         is( $account->balance, $replacement_amount, 'Balance is L' );
2414
2415         # Partially pay fee
2416         my $payment_amount = 27;
2417         my $payment        = $account->add_credit(
2418             {   amount => $payment_amount,
2419                 type   => 'payment',
2420                 interface => 'test',
2421             }
2422         );
2423         $payment->apply({ debits => $lost_fee_lines->reset, offset_type => 'Payment' });
2424
2425         is( $account->balance,
2426             $replacement_amount - $payment_amount,
2427             'Payment applied'
2428         );
2429
2430         my $manual_debit_amount = 80;
2431         $account->add_debit( { amount => $manual_debit_amount, type => 'overdue', interface =>'test' } );
2432
2433         is( $account->balance, $manual_debit_amount + $replacement_amount - $payment_amount, 'Manual debit applied' );
2434
2435         t::lib::Mocks::mock_preference( 'AccountAutoReconcile', 1 );
2436
2437         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item_id, $patron->id );
2438         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2439
2440         is( $account->balance, $manual_debit_amount - $payment_amount, 'Balance is PF - payment (CR)' );
2441
2442         my $manual_debit = Koha::Account::Lines->search({ borrowernumber => $patron->id, accounttype => 'OVERDUE', status => 'UNRETURNED' })->next;
2443         is( $manual_debit->amountoutstanding + 0, $manual_debit_amount - $payment_amount, 'reconcile_balance was called' );
2444     };
2445 };
2446
2447 subtest '_FixOverduesOnReturn' => sub {
2448     plan tests => 9;
2449
2450     my $manager = $builder->build_object({ class => "Koha::Patrons" });
2451     t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2452
2453     my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
2454
2455     my $branchcode  = $library2->{branchcode};
2456
2457     my $item = $builder->build_sample_item(
2458         {
2459             biblionumber     => $biblio->biblionumber,
2460             library          => $branchcode,
2461             replacementprice => 99.00,
2462             itype            => $itemtype,
2463         }
2464     );
2465
2466     my $patron = $builder->build( { source => 'Borrower' } );
2467
2468     ## Start with basic call, should just close out the open fine
2469     my $accountline = Koha::Account::Line->new(
2470         {
2471             borrowernumber => $patron->{borrowernumber},
2472             accounttype    => 'OVERDUE',
2473             status         => 'UNRETURNED',
2474             itemnumber     => $item->itemnumber,
2475             amount => 99.00,
2476             amountoutstanding => 99.00,
2477             interface => 'test',
2478         }
2479     )->store();
2480
2481     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber );
2482
2483     $accountline->_result()->discard_changes();
2484
2485     is( $accountline->amountoutstanding, '99.000000', 'Fine has the same amount outstanding as previously' );
2486     is( $accountline->status, 'RETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status RETURNED )');
2487
2488     ## Run again, with exemptfine enabled
2489     $accountline->set(
2490         {
2491             accounttype    => 'OVERDUE',
2492             status         => 'UNRETURNED',
2493             amountoutstanding => 99.00,
2494         }
2495     )->store();
2496
2497     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1 );
2498
2499     $accountline->_result()->discard_changes();
2500     my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
2501
2502     is( $accountline->amountoutstanding + 0, 0, 'Fine has been reduced to 0' );
2503     is( $accountline->status, 'FORGIVEN', 'Open fine ( account type OVERDUE ) has been set to fine forgiven ( status FORGIVEN )');
2504     is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
2505     is( $offset->amount, '-99.000000', "Amount of offset is correct" );
2506     my $credit = $offset->credit;
2507     is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
2508     is( $credit->amount, '-99.000000', "Credit amount is set correctly" );
2509     is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
2510 };
2511
2512 subtest 'Set waiting flag' => sub {
2513     plan tests => 4;
2514
2515     my $library_1 = $builder->build( { source => 'Branch' } );
2516     my $patron_1  = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2517     my $library_2 = $builder->build( { source => 'Branch' } );
2518     my $patron_2  = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2519
2520     my $biblio = $builder->build( { source => 'Biblio' } );
2521     my $biblioitem = $builder->build( { source => 'Biblioitem', value => { biblionumber => $biblio->{biblionumber} } } );
2522
2523     my $item = $builder->build(
2524         {
2525             source => 'Item',
2526             value  => {
2527                 homebranch    => $library_1->{branchcode},
2528                 holdingbranch => $library_1->{branchcode},
2529                 notforloan    => 0,
2530                 itemlost      => 0,
2531                 withdrawn     => 0,
2532                 biblionumber  => $biblioitem->{biblionumber},
2533             }
2534         }
2535     );
2536
2537     set_userenv( $library_2 );
2538     my $reserve_id = AddReserve(
2539         $library_2->{branchcode}, $patron_2->{borrowernumber}, $biblioitem->{biblionumber},
2540         '', 1, undef, undef, '', undef, $item->{itemnumber},
2541     );
2542
2543     set_userenv( $library_1 );
2544     my $do_transfer = 1;
2545     my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
2546     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2547     my $hold = Koha::Holds->find( $reserve_id );
2548     is( $hold->found, 'T', 'Hold is in transit' );
2549
2550     my ( $status ) = CheckReserves($item->{itemnumber});
2551     is( $status, 'Reserved', 'Hold is not waiting yet');
2552
2553     set_userenv( $library_2 );
2554     $do_transfer = 0;
2555     AddReturn( $item->{barcode}, $library_2->{branchcode} );
2556     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2557     $hold = Koha::Holds->find( $reserve_id );
2558     is( $hold->found, 'W', 'Hold is waiting' );
2559     ( $status ) = CheckReserves($item->{itemnumber});
2560     is( $status, 'Waiting', 'Now the hold is waiting');
2561 };
2562
2563 subtest 'Cancel transfers on lost items' => sub {
2564     plan tests => 5;
2565     my $library_1 = $builder->build( { source => 'Branch' } );
2566     my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2567     my $library_2 = $builder->build( { source => 'Branch' } );
2568     my $patron_2  = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2569     my $biblio = $builder->build( { source => 'Biblio' } );
2570     my $biblioitem = $builder->build( { source => 'Biblioitem', value => { biblionumber => $biblio->{biblionumber} } } );
2571     my $item = $builder->build(
2572         {
2573             source => 'Item',
2574             value => {
2575                 homebranch => $library_1->{branchcode},
2576                 holdingbranch => $library_1->{branchcode},
2577                 notforloan => 0,
2578                 itemlost => 0,
2579                 withdrawn => 0,
2580                 biblionumber => $biblioitem->{biblionumber},
2581             }
2582         }
2583     );
2584
2585     set_userenv( $library_2 );
2586     my $reserve_id = AddReserve(
2587         $library_2->{branchcode}, $patron_2->{borrowernumber}, $biblioitem->{biblionumber}, '', 1, undef, undef, '', undef, $item->{itemnumber},
2588     );
2589
2590     #Return book and add transfer
2591     set_userenv( $library_1 );
2592     my $do_transfer = 1;
2593     my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
2594     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2595     C4::Circulation::transferbook( $library_2->{branchcode}, $item->{barcode} );
2596     my $hold = Koha::Holds->find( $reserve_id );
2597     is( $hold->found, 'T', 'Hold is in transit' );
2598
2599     #Check transfer exists and the items holding branch is the transfer destination branch before marking it as lost
2600     my ($datesent,$frombranch,$tobranch) = GetTransfers($item->{itemnumber});
2601     is( $tobranch, $library_2->{branchcode}, 'The transfer record exists in the branchtransfers table');
2602     my $itemcheck = Koha::Items->find($item->{itemnumber});
2603     is( $itemcheck->holdingbranch, $library_2->{branchcode}, 'Items holding branch is the transfers destination branch before it is marked as lost' );
2604
2605     #Simulate item being marked as lost and confirm the transfer is deleted and the items holding branch is the transfers source branch
2606     ModItem( { itemlost => 1 }, $biblio->{biblionumber}, $item->{itemnumber} );
2607     LostItem( $item->{itemnumber}, 'test', 1 );
2608     ($datesent,$frombranch,$tobranch) = GetTransfers($item->{itemnumber});
2609     is( $tobranch, undef, 'The transfer on the lost item has been deleted as the LostItemCancelOutstandingTransfer is enabled');
2610     $itemcheck = Koha::Items->find($item->{itemnumber});
2611     is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Lost item with cancelled hold has holding branch equallying the transfers source branch' );
2612 };
2613
2614 subtest 'CanBookBeIssued | is_overdue' => sub {
2615     plan tests => 3;
2616
2617     # Set a simple circ policy
2618     $dbh->do('DELETE FROM issuingrules');
2619     $dbh->do(
2620     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
2621                                     issuelength, lengthunit,
2622                                     renewalsallowed, renewalperiod,
2623                                     norenewalbefore, auto_renew,
2624                                     fine, chargeperiod)
2625           VALUES (?, ?, ?, ?,
2626                   ?, ?,
2627                   ?, ?,
2628                   ?, ?,
2629                   ?, ?
2630                  )
2631         },
2632         {},
2633         '*',   '*', '*', 25,
2634         14,  'days',
2635         1,     7,
2636         undef, 0,
2637         .10,   1
2638     );
2639
2640     my $five_days_go = output_pref({ dt => dt_from_string->add( days => 5 ), dateonly => 1});
2641     my $ten_days_go  = output_pref({ dt => dt_from_string->add( days => 10), dateonly => 1 });
2642     my $library = $builder->build( { source => 'Branch' } );
2643     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2644
2645     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
2646     my $item = $builder->build(
2647         {
2648             source => 'Item',
2649             value  => {
2650                 homebranch    => $library->{branchcode},
2651                 holdingbranch => $library->{branchcode},
2652                 notforloan    => 0,
2653                 itemlost      => 0,
2654                 withdrawn     => 0,
2655                 biblionumber  => $biblioitem->{biblionumber},
2656             }
2657         }
2658     );
2659
2660     my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $five_days_go ); # date due was 10d ago
2661     my $actualissue = Koha::Checkouts->find( { itemnumber => $item->{itemnumber} } );
2662     is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
2663     my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->{barcode},$ten_days_go, undef, undef, undef);
2664     is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
2665     is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
2666 };
2667
2668 subtest 'ItemsDeniedRenewal preference' => sub {
2669     plan tests => 18;
2670
2671     C4::Context->set_preference('ItemsDeniedRenewal','');
2672
2673     my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
2674     $dbh->do(
2675         q{
2676         INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, issuelength, lengthunit, renewalsallowed, renewalperiod,
2677                     norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
2678         },
2679         {},
2680         '*', $idr_lib->branchcode, '*', 25,
2681         14,  'days',
2682         10,   7,
2683         undef,  0,
2684         .10, 1
2685     );
2686
2687     my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
2688         homebranch => $idr_lib->branchcode,
2689         withdrawn => 1,
2690         itype => 'HIDE',
2691         location => 'PROC',
2692         itemcallnumber => undef,
2693         itemnotes => "",
2694         }
2695     });
2696     my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
2697         homebranch => $idr_lib->branchcode,
2698         withdrawn => 0,
2699         itype => 'NOHIDE',
2700         location => 'NOPROC'
2701         }
2702     });
2703
2704     my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
2705         branchcode => $idr_lib->branchcode,
2706         }
2707     });
2708     my $future = dt_from_string->add( days => 1 );
2709     my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
2710         returndate => undef,
2711         renewals => 0,
2712         auto_renew => 0,
2713         borrowernumber => $idr_borrower->borrowernumber,
2714         itemnumber => $deny_book->itemnumber,
2715         onsite_checkout => 0,
2716         date_due => $future,
2717         }
2718     });
2719     my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
2720         returndate => undef,
2721         renewals => 0,
2722         auto_renew => 0,
2723         borrowernumber => $idr_borrower->borrowernumber,
2724         itemnumber => $allow_book->itemnumber,
2725         onsite_checkout => 0,
2726         date_due => $future,
2727         }
2728     });
2729
2730     my $idr_rules;
2731
2732     my ( $idr_mayrenew, $idr_error ) =
2733     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2734     is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
2735     is( $idr_error, undef, 'Renewal allowed when no rules' );
2736
2737     $idr_rules="withdrawn: [1]";
2738
2739     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2740     ( $idr_mayrenew, $idr_error ) =
2741     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2742     is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
2743     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
2744     ( $idr_mayrenew, $idr_error ) =
2745     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2746     is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
2747     is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
2748
2749     $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
2750
2751     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2752     ( $idr_mayrenew, $idr_error ) =
2753     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2754     is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
2755     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
2756     ( $idr_mayrenew, $idr_error ) =
2757     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2758     is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
2759     is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
2760
2761     $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
2762
2763     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2764     ( $idr_mayrenew, $idr_error ) =
2765     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2766     is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
2767     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
2768     ( $idr_mayrenew, $idr_error ) =
2769     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2770     is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
2771     is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
2772
2773     $idr_rules="itemcallnumber: [NULL]";
2774     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2775     ( $idr_mayrenew, $idr_error ) =
2776     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2777     is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
2778     $idr_rules="itemcallnumber: ['']";
2779     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2780     ( $idr_mayrenew, $idr_error ) =
2781     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2782     is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
2783
2784     $idr_rules="itemnotes: [NULL]";
2785     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2786     ( $idr_mayrenew, $idr_error ) =
2787     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2788     is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
2789     $idr_rules="itemnotes: ['']";
2790     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2791     ( $idr_mayrenew, $idr_error ) =
2792     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2793     is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
2794 };
2795
2796 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
2797     plan tests => 2;
2798
2799     t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
2800     my $library = $builder->build( { source => 'Branch' } );
2801     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
2802
2803     my $itemtype = $builder->build(
2804         {
2805             source => 'Itemtype',
2806             value  => { notforloan => undef, }
2807         }
2808     );
2809
2810     my $biblioitem = $builder->build( { source => 'Biblioitem', value => { itemtype => $itemtype->{itemtype} } } );
2811     my $item = $builder->build_object(
2812         {
2813             class => 'Koha::Items',
2814             value  => {
2815                 homebranch    => $library->{branchcode},
2816                 holdingbranch => $library->{branchcode},
2817                 notforloan    => 0,
2818                 itemlost      => 0,
2819                 withdrawn     => 0,
2820                 biblionumber  => $biblioitem->{biblionumber},
2821                 biblioitemnumber => $biblioitem->{biblioitemnumber},
2822             }
2823         }
2824     )->store;
2825
2826     my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2827     is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2828     is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2829 };
2830
2831 subtest 'CanBookBeIssued | notforloan' => sub {
2832     plan tests => 2;
2833
2834     t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
2835
2836     my $library = $builder->build( { source => 'Branch' } );
2837     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
2838
2839     my $itemtype = $builder->build(
2840         {
2841             source => 'Itemtype',
2842             value  => { notforloan => undef, }
2843         }
2844     );
2845
2846     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
2847     my $item = $builder->build_object(
2848         {
2849             class => 'Koha::Items',
2850             value  => {
2851                 homebranch    => $library->{branchcode},
2852                 holdingbranch => $library->{branchcode},
2853                 notforloan    => 0,
2854                 itemlost      => 0,
2855                 withdrawn     => 0,
2856                 itype         => $itemtype->{itemtype},
2857                 biblionumber  => $biblioitem->{biblionumber},
2858                 biblioitemnumber => $biblioitem->{biblioitemnumber},
2859             }
2860         }
2861     )->store;
2862
2863     my ( $issuingimpossible, $needsconfirmation );
2864
2865
2866     subtest 'item-level_itypes = 1' => sub {
2867         plan tests => 6;
2868
2869         t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
2870         # Is for loan at item type and item level
2871         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2872         is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2873         is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2874
2875         # not for loan at item type level
2876         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
2877         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2878         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2879         is_deeply(
2880             $issuingimpossible,
2881             { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
2882             'Item can not be issued, not for loan at item type level'
2883         );
2884
2885         # not for loan at item level
2886         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
2887         $item->notforloan( 1 )->store;
2888         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2889         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2890         is_deeply(
2891             $issuingimpossible,
2892             { NOT_FOR_LOAN => 1, item_notforloan => 1 },
2893             'Item can not be issued, not for loan at item type level'
2894         );
2895     };
2896
2897     subtest 'item-level_itypes = 0' => sub {
2898         plan tests => 6;
2899
2900         t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
2901
2902         # We set another itemtype for biblioitem
2903         my $itemtype = $builder->build(
2904             {
2905                 source => 'Itemtype',
2906                 value  => { notforloan => undef, }
2907             }
2908         );
2909
2910         # for loan at item type and item level
2911         $item->notforloan(0)->store;
2912         $item->biblioitem->itemtype($itemtype->{itemtype})->store;
2913         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2914         is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2915         is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2916
2917         # not for loan at item type level
2918         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
2919         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2920         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2921         is_deeply(
2922             $issuingimpossible,
2923             { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
2924             'Item can not be issued, not for loan at item type level'
2925         );
2926
2927         # not for loan at item level
2928         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
2929         $item->notforloan( 1 )->store;
2930         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2931         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2932         is_deeply(
2933             $issuingimpossible,
2934             { NOT_FOR_LOAN => 1, item_notforloan => 1 },
2935             'Item can not be issued, not for loan at item type level'
2936         );
2937     };
2938
2939     # TODO test with AllowNotForLoanOverride = 1
2940 };
2941
2942 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
2943     plan tests => 1;
2944
2945     t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
2946     my $item = $builder->build_object({ class => 'Koha::Items', value  => { onloan => '2018-01-01' }});
2947     AddReturn( $item->barcode, $item->homebranch );
2948     $item->discard_changes; # refresh
2949     is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
2950 };
2951
2952 $schema->storage->txn_rollback;
2953 C4::Context->clear_syspref_cache();
2954 $cache->clear_from_cache('single_holidays');
2955
2956 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
2957
2958     plan tests => 13;
2959
2960     $schema->storage->txn_begin;
2961
2962     t::lib::Mocks::mock_preference('item-level_itypes', 1);
2963
2964     my $issuing_charges = 15;
2965     my $title   = 'A title';
2966     my $author  = 'Author, An';
2967     my $barcode = 'WHATARETHEODDS';
2968
2969     my $circ = Test::MockModule->new('C4::Circulation');
2970     $circ->mock(
2971         'GetIssuingCharges',
2972         sub {
2973             return $issuing_charges;
2974         }
2975     );
2976
2977     my $library  = $builder->build_object({ class => 'Koha::Libraries' });
2978     my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
2979     my $patron   = $builder->build_object({
2980         class => 'Koha::Patrons',
2981         value => { branchcode => $library->id }
2982     });
2983
2984     my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
2985     my ( undef, undef, $item_id ) = AddItem(
2986         {
2987             homebranch       => $library->id,
2988             holdingbranch    => $library->id,
2989             barcode          => $barcode,
2990             replacementprice => 23.00,
2991             itype            => $itemtype->id
2992         },
2993         $biblio->biblionumber
2994     );
2995     my $item = Koha::Items->find( $item_id );
2996
2997     my $context = Test::MockModule->new('C4::Context');
2998     $context->mock( userenv => { branch => $library->id } );
2999
3000     # Check the item out
3001     AddIssue( $patron->unblessed, $item->barcode );
3002     t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
3003     my $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
3004     my %params_renewal = (
3005         timestamp => { -like => $date . "%" },
3006         module => "CIRCULATION",
3007         action => "RENEWAL",
3008     );
3009     my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
3010     AddRenewal( $patron->id, $item->id, $library->id );
3011     my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3012     is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
3013
3014     my $checkouts = $patron->checkouts;
3015     # The following will fail if run on 00:00:00
3016     unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
3017
3018     t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
3019     $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
3020     $old_log_size = Koha::ActionLogs->count( \%params_renewal );
3021     AddRenewal( $patron->id, $item->id, $library->id );
3022     $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3023     is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
3024
3025     my $lines = Koha::Account::Lines->search({
3026         borrowernumber => $patron->id,
3027         itemnumber     => $item->id
3028     });
3029
3030     is( $lines->count, 3 );
3031
3032     my $line = $lines->next;
3033     is( $line->accounttype, 'Rent',       'The issuing charge generates an accountline' );
3034     is( $line->branchcode,  $library->id, 'AddIssuingCharge correctly sets branchcode' );
3035     is( $line->description, 'Rental',     'AddIssuingCharge set a hardcoded description for the accountline' );
3036
3037     $line = $lines->next;
3038     is( $line->accounttype, 'Rent', 'Fine on renewed item is closed out properly' );
3039     is( $line->branchcode,  $library->id, 'AddRenewal correctly sets branchcode' );
3040     is( $line->description, "Renewal of Rental Item $title $barcode", 'AddRenewal set a hardcoded description for the accountline' );
3041
3042     $line = $lines->next;
3043     is( $line->accounttype, 'Rent', 'Fine on renewed item is closed out properly' );
3044     is( $line->branchcode,  $library->id, 'AddRenewal correctly sets branchcode' );
3045     is( $line->description, "Renewal of Rental Item $title $barcode", 'AddRenewal set a hardcoded description for the accountline' );
3046
3047     $schema->storage->txn_rollback;
3048 };
3049
3050 subtest 'ProcessOfflinePayment() tests' => sub {
3051
3052     plan tests => 4;
3053
3054     $schema->storage->txn_begin;
3055
3056     my $amount = 123;
3057
3058     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
3059     my $library = $builder->build_object({ class => 'Koha::Libraries' });
3060     my $result  = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
3061
3062     is( $result, 'Success.', 'The right string is returned' );
3063
3064     my $lines = $patron->account->lines;
3065     is( $lines->count, 1, 'line created correctly');
3066
3067     my $line = $lines->next;
3068     is( $line->amount+0, $amount * -1, 'amount picked from params' );
3069     is( $line->branchcode, $library->id, 'branchcode set correctly' );
3070
3071     $schema->storage->txn_rollback;
3072 };
3073
3074
3075
3076 sub set_userenv {
3077     my ( $library ) = @_;
3078     t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
3079 }
3080
3081 sub str {
3082     my ( $error, $question, $alert ) = @_;
3083     my $s;
3084     $s  = %$error    ? ' (error: '    . join( ' ', keys %$error    ) . ')' : '';
3085     $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
3086     $s .= %$alert    ? ' (alert: '    . join( ' ', keys %$alert    ) . ')' : '';
3087     return $s;
3088 }
3089
3090 sub test_debarment_on_checkout {
3091     my ($params) = @_;
3092     my $item     = $params->{item};
3093     my $library  = $params->{library};
3094     my $patron   = $params->{patron};
3095     my $due_date = $params->{due_date} || dt_from_string;
3096     my $return_date = $params->{return_date} || dt_from_string;
3097     my $expected_expiration_date = $params->{expiration_date};
3098
3099     $expected_expiration_date = output_pref(
3100         {
3101             dt         => $expected_expiration_date,
3102             dateformat => 'sql',
3103             dateonly   => 1,
3104         }
3105     );
3106     my @caller      = caller;
3107     my $line_number = $caller[2];
3108     AddIssue( $patron, $item->{barcode}, $due_date );
3109
3110     my ( undef, $message ) = AddReturn( $item->{barcode}, $library->{branchcode}, undef, $return_date );
3111     is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' )
3112         or diag('AddReturn returned message ' . Dumper $message );
3113     my $debarments = Koha::Patron::Debarments::GetDebarments(
3114         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
3115     is( scalar(@$debarments), 1, 'Test at line ' . $line_number );
3116
3117     is( $debarments->[0]->{expiration},
3118         $expected_expiration_date, 'Test at line ' . $line_number );
3119     Koha::Patron::Debarments::DelUniqueDebarment(
3120         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
3121 };
3122
3123 subtest 'Incremented fee tests' => sub {
3124     plan tests => 11;
3125
3126     t::lib::Mocks::mock_preference('item-level_itypes', 1);
3127
3128     my $library = $builder->build_object( { class => 'Koha::Libraries' } )->store;
3129
3130     my $module = new Test::MockModule('C4::Context');
3131     $module->mock('userenv', sub { { branch => $library->id } });
3132
3133     my $patron = $builder->build_object(
3134         {
3135             class => 'Koha::Patrons',
3136             value => { categorycode => $patron_category->{categorycode} }
3137         }
3138     )->store;
3139
3140     my $itemtype = $builder->build_object(
3141         {
3142             class => 'Koha::ItemTypes',
3143             value  => {
3144                 notforloan          => undef,
3145                 rentalcharge        => 0,
3146                 rentalcharge_daily => 1.000000
3147             }
3148         }
3149     )->store;
3150
3151     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
3152     my $item = $builder->build_object(
3153         {
3154             class => 'Koha::Items',
3155             value => {
3156                 homebranch       => $library->id,
3157                 holdingbranch    => $library->id,
3158                 notforloan       => 0,
3159                 itemlost         => 0,
3160                 withdrawn        => 0,
3161                 itype            => $itemtype->id,
3162                 biblionumber     => $biblioitem->{biblionumber},
3163                 biblioitemnumber => $biblioitem->{biblioitemnumber},
3164             }
3165         }
3166     )->store;
3167
3168     is( $itemtype->rentalcharge_daily, '1.000000', 'Daily rental charge stored and retreived correctly' );
3169     is( $item->effective_itemtype, $itemtype->id, "Itemtype set correctly for item");
3170
3171     my $dt_from = dt_from_string();
3172     my $dt_to = dt_from_string()->add( days => 7 );
3173     my $dt_to_renew = dt_from_string()->add( days => 13 );
3174
3175     t::lib::Mocks::mock_preference('finesCalendar', 'ignoreCalendar');
3176     my $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3177     my $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3178     is( $accountline->amount, '7.000000', "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar" );
3179     $accountline->delete();
3180     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3181     $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3182     is( $accountline->amount, '6.000000', "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar, for renewal" );
3183     $accountline->delete();
3184     $issue->delete();
3185
3186     t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
3187     $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3188     $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3189     is( $accountline->amount, '7.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed" );
3190     $accountline->delete();
3191     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3192     $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3193     is( $accountline->amount, '6.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed, for renewal" );
3194     $accountline->delete();
3195     $issue->delete();
3196
3197     my $calendar = C4::Calendar->new( branchcode => $library->id );
3198     $calendar->insert_week_day_holiday(
3199         weekday     => 3,
3200         title       => 'Test holiday',
3201         description => 'Test holiday'
3202     );
3203     $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3204     $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3205     is( $accountline->amount, '6.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed Wednesdays" );
3206     $accountline->delete();
3207     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3208     $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3209     is( $accountline->amount, '5.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed Wednesdays, for renewal" );
3210     $accountline->delete();
3211     $issue->delete();
3212
3213     $itemtype->rentalcharge('2.000000')->store;
3214     is( $itemtype->rentalcharge, '2.000000', 'Rental charge updated and retreived correctly' );
3215     $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from);
3216     my $accountlines = Koha::Account::Lines->search({ itemnumber => $item->id });
3217     is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly");
3218     $accountlines->delete();
3219     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3220     $accountlines = Koha::Account::Lines->search({ itemnumber => $item->id });
3221     is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly, for renewal");
3222     $accountlines->delete();
3223     $issue->delete();
3224 };
3225
3226 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
3227     plan tests => 2;
3228
3229     t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
3230     t::lib::Mocks::mock_preference('item-level_itypes', 1);
3231
3232     my $library =
3233       $builder->build_object( { class => 'Koha::Libraries' } )->store;
3234     my $patron = $builder->build_object(
3235         {
3236             class => 'Koha::Patrons',
3237             value => { categorycode => $patron_category->{categorycode} }
3238         }
3239     )->store;
3240
3241     my $itemtype = $builder->build_object(
3242         {
3243             class => 'Koha::ItemTypes',
3244             value => {
3245                 notforloan             => 0,
3246                 rentalcharge           => 0,
3247                 rentalcharge_daily => 0
3248             }
3249         }
3250     );
3251
3252     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
3253     my $item = $builder->build_object(
3254         {
3255             class => 'Koha::Items',
3256             value  => {
3257                 homebranch    => $library->id,
3258                 holdingbranch => $library->id,
3259                 notforloan    => 0,
3260                 itemlost      => 0,
3261                 withdrawn     => 0,
3262                 itype         => $itemtype->id,
3263                 biblionumber  => $biblioitem->{biblionumber},
3264                 biblioitemnumber => $biblioitem->{biblioitemnumber},
3265             }
3266         }
3267     )->store;
3268
3269     my ( $issuingimpossible, $needsconfirmation );
3270     my $dt_from = dt_from_string();
3271     my $dt_due = dt_from_string()->add( days => 3 );
3272
3273     $itemtype->rentalcharge('1.000000')->store;
3274     ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3275     is_deeply( $needsconfirmation, { RENTALCHARGE => '1' }, 'Item needs rentalcharge confirmation to be issued' );
3276     $itemtype->rentalcharge('0')->store;
3277     $itemtype->rentalcharge_daily('1.000000')->store;
3278     ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3279     is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
3280     $itemtype->rentalcharge_daily('0')->store;
3281 };