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