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