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