Bug 12768: Replacement cost and processing fee management
[koha.git] / t / db_dependent / Circulation.t
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19
20 use Test::More tests => 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 => { categorycode => '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     ModItem({ itype => 'BK' }, $biblionumber, $itemnumber, 1);
782     LostItem( $itemnumber, 1 );
783
784     my $item = Koha::Database->new()->schema()->resultset('Item')->find($itemnumber);
785     ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
786
787     my $total_due = $dbh->selectrow_array(
788         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
789         undef, $renewing_borrower->{borrowernumber}
790     );
791
792     ok( $total_due == 12, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
793
794     C4::Context->dbh->do("DELETE FROM accountlines");
795
796     t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
797     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
798
799     C4::Overdues::UpdateFine(
800         {
801             issue_id       => $issue2->id(),
802             itemnumber     => $itemnumber2,
803             borrowernumber => $renewing_borrower->{borrowernumber},
804             amount         => 15.00,
805             type           => q{},
806             due            => Koha::DateUtils::output_pref($datedue)
807         }
808     );
809
810     LostItem( $itemnumber2, 0 );
811
812     my $item2 = Koha::Database->new()->schema()->resultset('Item')->find($itemnumber2);
813     ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
814
815     $total_due = $dbh->selectrow_array(
816         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
817         undef, $renewing_borrower->{borrowernumber}
818     );
819
820     ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
821
822     my $future = dt_from_string();
823     $future->add( days => 7 );
824     my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
825     ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
826
827     # Users cannot renew any item if there is an overdue item
828     t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
829     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber6);
830     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
831     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber7);
832     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
833
834   }
835
836 {
837     # GetUpcomingDueIssues tests
838     my $barcode  = 'R00000342';
839     my $barcode2 = 'R00000343';
840     my $barcode3 = 'R00000344';
841     my $branch   = $library2->{branchcode};
842
843     #Create another record
844     my $biblio2 = MARC::Record->new();
845     my $title2 = 'Something is worng here';
846     $biblio2->append_fields(
847         MARC::Field->new('100', ' ', ' ', a => 'Anonymous'),
848         MARC::Field->new('245', ' ', ' ', a => $title2),
849     );
850     my ($biblionumber2, $biblioitemnumber2) = AddBiblio($biblio2, '');
851
852     #Create third item
853     AddItem(
854         {
855             homebranch       => $branch,
856             holdingbranch    => $branch,
857             barcode          => $barcode3,
858             itype            => $itemtype
859         },
860         $biblionumber2
861     );
862
863     # Create a borrower
864     my %a_borrower_data = (
865         firstname =>  'Fridolyn',
866         surname => 'SOMERS',
867         categorycode => $patron_category->{categorycode},
868         branchcode => $branch,
869     );
870
871     my $a_borrower_borrowernumber = AddMember(%a_borrower_data);
872     my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
873
874     my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
875     my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
876     my $today = DateTime->today(time_zone => C4::Context->tz());
877
878     my $issue = AddIssue( $a_borrower, $barcode, $yesterday );
879     my $datedue = dt_from_string( $issue->date_due() );
880     my $issue2 = AddIssue( $a_borrower, $barcode2, $two_days_ahead );
881     my $datedue2 = dt_from_string( $issue->date_due() );
882
883     my $upcoming_dues;
884
885     # GetUpcomingDueIssues tests
886     for my $i(0..1) {
887         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
888         is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
889     }
890
891     #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
892     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
893     is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
894
895     for my $i(3..5) {
896         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
897         is ( scalar( @$upcoming_dues ), 1,
898             "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
899     }
900
901     # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
902
903     my $issue3 = AddIssue( $a_borrower, $barcode3, $today );
904
905     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
906     is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
907
908     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
909     is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
910
911     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
912     is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
913
914     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 }  );
915     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
916
917     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
918     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
919
920     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
921     is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
922
923 }
924
925 {
926     my $barcode  = '1234567890';
927     my $branch   = $library2->{branchcode};
928
929     my $biblio = MARC::Record->new();
930     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
931
932     #Create third item
933     my ( undef, undef, $itemnumber ) = AddItem(
934         {
935             homebranch       => $branch,
936             holdingbranch    => $branch,
937             barcode          => $barcode,
938             itype            => $itemtype
939         },
940         $biblionumber
941     );
942
943     # Create a borrower
944     my %a_borrower_data = (
945         firstname =>  'Kyle',
946         surname => 'Hall',
947         categorycode => $patron_category->{categorycode},
948         branchcode => $branch,
949     );
950
951     my $borrowernumber = AddMember(%a_borrower_data);
952
953     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
954     my $issue = AddIssue( $borrower, $barcode );
955     UpdateFine(
956         {
957             issue_id       => $issue->id(),
958             itemnumber     => $itemnumber,
959             borrowernumber => $borrowernumber,
960             amount         => 0,
961             type           => q{}
962         }
963     );
964
965     my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $itemnumber );
966     my $count = $hr->{count};
967
968     is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
969 }
970
971 {
972     $dbh->do('DELETE FROM issues');
973     $dbh->do('DELETE FROM items');
974     $dbh->do('DELETE FROM issuingrules');
975     $dbh->do(
976         q{
977         INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, maxissueqty, issuelength, lengthunit, renewalsallowed, renewalperiod,
978                     norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
979         },
980         {},
981         '*', '*', '*', 25,
982         20,  14,  'days',
983         1,   7,
984         undef,  0,
985         .10, 1
986     );
987     my $biblio = MARC::Record->new();
988     my ( $biblionumber, $biblioitemnumber ) = AddBiblio( $biblio, '' );
989
990     my $barcode1 = '1234';
991     my ( undef, undef, $itemnumber1 ) = AddItem(
992         {
993             homebranch    => $library2->{branchcode},
994             holdingbranch => $library2->{branchcode},
995             barcode       => $barcode1,
996             itype         => $itemtype
997         },
998         $biblionumber
999     );
1000     my $barcode2 = '4321';
1001     my ( undef, undef, $itemnumber2 ) = AddItem(
1002         {
1003             homebranch    => $library2->{branchcode},
1004             holdingbranch => $library2->{branchcode},
1005             barcode       => $barcode2,
1006             itype         => $itemtype
1007         },
1008         $biblionumber
1009     );
1010
1011     my $borrowernumber1 = AddMember(
1012         firstname    => 'Kyle',
1013         surname      => 'Hall',
1014         categorycode => $patron_category->{categorycode},
1015         branchcode   => $library2->{branchcode},
1016     );
1017     my $borrowernumber2 = AddMember(
1018         firstname    => 'Chelsea',
1019         surname      => 'Hall',
1020         categorycode => $patron_category->{categorycode},
1021         branchcode   => $library2->{branchcode},
1022     );
1023
1024     my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1025     my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1026
1027     my $issue = AddIssue( $borrower1, $barcode1 );
1028
1029     my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1030     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1031
1032     AddReserve(
1033         $library2->{branchcode}, $borrowernumber2, $biblionumber,
1034         '',  1, undef, undef, '',
1035         undef, undef, undef
1036     );
1037
1038     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1039     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1040     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1041     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1042
1043     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1044     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1045     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1046     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1047
1048     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1049     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1050     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1051     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1052
1053     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1054     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1055     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1056     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1057
1058     # Setting item not checked out to be not for loan but holdable
1059     ModItem({ notforloan => -1 }, $biblionumber, $itemnumber2);
1060
1061     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1062     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' );
1063 }
1064
1065 {
1066     # Don't allow renewing onsite checkout
1067     my $barcode  = 'R00000XXX';
1068     my $branch   = $library->{branchcode};
1069
1070     #Create another record
1071     my $biblio = MARC::Record->new();
1072     $biblio->append_fields(
1073         MARC::Field->new('100', ' ', ' ', a => 'Anonymous'),
1074         MARC::Field->new('245', ' ', ' ', a => 'A title'),
1075     );
1076     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
1077
1078     my (undef, undef, $itemnumber) = AddItem(
1079         {
1080             homebranch       => $branch,
1081             holdingbranch    => $branch,
1082             barcode          => $barcode,
1083             itype            => $itemtype
1084         },
1085         $biblionumber
1086     );
1087
1088     my $borrowernumber = AddMember(
1089         firstname =>  'fn',
1090         surname => 'dn',
1091         categorycode => $patron_category->{categorycode},
1092         branchcode => $branch,
1093     );
1094
1095     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1096
1097     my $issue = AddIssue( $borrower, $barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1098     my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $itemnumber );
1099     is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1100     is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1101 }
1102
1103 {
1104     my $library = $builder->build({ source => 'Branch' });
1105
1106     my $biblio = MARC::Record->new();
1107     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
1108
1109     my $barcode = 'just a barcode';
1110     my ( undef, undef, $itemnumber ) = AddItem(
1111         {
1112             homebranch       => $library->{branchcode},
1113             holdingbranch    => $library->{branchcode},
1114             barcode          => $barcode,
1115             itype            => $itemtype
1116         },
1117         $biblionumber,
1118     );
1119
1120     my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1121
1122     my $issue = AddIssue( $patron, $barcode );
1123     UpdateFine(
1124         {
1125             issue_id       => $issue->id(),
1126             itemnumber     => $itemnumber,
1127             borrowernumber => $patron->{borrowernumber},
1128             amount         => 1,
1129             type           => q{}
1130         }
1131     );
1132     UpdateFine(
1133         {
1134             issue_id       => $issue->id(),
1135             itemnumber     => $itemnumber,
1136             borrowernumber => $patron->{borrowernumber},
1137             amount         => 2,
1138             type           => q{}
1139         }
1140     );
1141     is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1142 }
1143
1144 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1145     plan tests => 23;
1146
1147     my $homebranch    = $builder->build( { source => 'Branch' } );
1148     my $holdingbranch = $builder->build( { source => 'Branch' } );
1149     my $otherbranch   = $builder->build( { source => 'Branch' } );
1150     my $patron_1      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1151     my $patron_2      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1152
1153     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1154     my $item = $builder->build(
1155         {   source => 'Item',
1156             value  => {
1157                 homebranch    => $homebranch->{branchcode},
1158                 holdingbranch => $holdingbranch->{branchcode},
1159                 notforloan    => 0,
1160                 itemlost      => 0,
1161                 withdrawn     => 0,
1162                 restricted    => 0,
1163                 biblionumber  => $biblioitem->{biblionumber}
1164             }
1165         }
1166     );
1167
1168     set_userenv($holdingbranch);
1169
1170     my $issue = AddIssue( $patron_1, $item->{barcode} );
1171     is( ref($issue), 'Koha::Schema::Result::Issue' );    # FIXME Should be Koha::Checkout
1172
1173     my ( $error, $question, $alerts );
1174
1175     # AllowReturnToBranch == anywhere
1176     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1177     ## Can be issued from homebranch
1178     set_userenv($homebranch);
1179     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1180     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1181     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1182     ## Can be issued from holdingbranch
1183     set_userenv($holdingbranch);
1184     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1185     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1186     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1187     ## Can be issued from another branch
1188     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1189     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1190     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1191
1192     # AllowReturnToBranch == holdingbranch
1193     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1194     ## Cannot be issued from homebranch
1195     set_userenv($homebranch);
1196     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1197     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1198     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1199     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
1200     ## Can be issued from holdinbranch
1201     set_userenv($holdingbranch);
1202     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1203     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1204     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1205     ## Cannot be issued from another branch
1206     set_userenv($otherbranch);
1207     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1208     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1209     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1210     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
1211
1212     # AllowReturnToBranch == homebranch
1213     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1214     ## Can be issued from holdinbranch
1215     set_userenv($homebranch);
1216     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1217     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1218     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1219     ## Cannot be issued from holdinbranch
1220     set_userenv($holdingbranch);
1221     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1222     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1223     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1224     is( $error->{branch_to_return},         $homebranch->{branchcode} );
1225     ## Cannot be issued from holdinbranch
1226     set_userenv($otherbranch);
1227     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1228     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1229     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1230     is( $error->{branch_to_return},         $homebranch->{branchcode} );
1231
1232     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1233 };
1234
1235 subtest 'AddIssue & AllowReturnToBranch' => sub {
1236     plan tests => 9;
1237
1238     my $homebranch    = $builder->build( { source => 'Branch' } );
1239     my $holdingbranch = $builder->build( { source => 'Branch' } );
1240     my $otherbranch   = $builder->build( { source => 'Branch' } );
1241     my $patron_1      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1242     my $patron_2      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1243
1244     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1245     my $item = $builder->build(
1246         {   source => 'Item',
1247             value  => {
1248                 homebranch    => $homebranch->{branchcode},
1249                 holdingbranch => $holdingbranch->{branchcode},
1250                 notforloan    => 0,
1251                 itemlost      => 0,
1252                 withdrawn     => 0,
1253                 biblionumber  => $biblioitem->{biblionumber}
1254             }
1255         }
1256     );
1257
1258     set_userenv($holdingbranch);
1259
1260     my $ref_issue = 'Koha::Schema::Result::Issue'; # FIXME Should be Koha::Checkout
1261     my $issue = AddIssue( $patron_1, $item->{barcode} );
1262
1263     my ( $error, $question, $alerts );
1264
1265     # AllowReturnToBranch == homebranch
1266     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1267     ## Can be issued from homebranch
1268     set_userenv($homebranch);
1269     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1270     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1271     ## Can be issued from holdinbranch
1272     set_userenv($holdingbranch);
1273     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1274     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1275     ## Can be issued from another branch
1276     set_userenv($otherbranch);
1277     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1278     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1279
1280     # AllowReturnToBranch == holdinbranch
1281     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1282     ## Cannot be issued from homebranch
1283     set_userenv($homebranch);
1284     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1285     ## Can be issued from holdingbranch
1286     set_userenv($holdingbranch);
1287     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1288     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1289     ## Cannot be issued from another branch
1290     set_userenv($otherbranch);
1291     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1292
1293     # AllowReturnToBranch == homebranch
1294     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1295     ## Can be issued from homebranch
1296     set_userenv($homebranch);
1297     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1298     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1299     ## Cannot be issued from holdinbranch
1300     set_userenv($holdingbranch);
1301     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1302     ## Cannot be issued from another branch
1303     set_userenv($otherbranch);
1304     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1305     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1306 };
1307
1308 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1309     plan tests => 8;
1310
1311     my $library = $builder->build( { source => 'Branch' } );
1312     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1313
1314     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1315     my $item_1 = $builder->build(
1316         {   source => 'Item',
1317             value  => {
1318                 homebranch    => $library->{branchcode},
1319                 holdingbranch => $library->{branchcode},
1320                 notforloan    => 0,
1321                 itemlost      => 0,
1322                 withdrawn     => 0,
1323                 restricted    => 0,
1324                 biblionumber  => $biblioitem_1->{biblionumber}
1325             }
1326         }
1327     );
1328     my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1329     my $item_2 = $builder->build(
1330         {   source => 'Item',
1331             value  => {
1332                 homebranch    => $library->{branchcode},
1333                 holdingbranch => $library->{branchcode},
1334                 notforloan    => 0,
1335                 itemlost      => 0,
1336                 withdrawn     => 0,
1337                 restricted    => 0,
1338                 biblionumber  => $biblioitem_2->{biblionumber}
1339             }
1340         }
1341     );
1342
1343     my ( $error, $question, $alerts );
1344
1345     # Patron cannot issue item_1, they have overdues
1346     my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1347     my $issue = AddIssue( $patron, $item_1->{barcode}, $yesterday );    # Add an overdue
1348
1349     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1350     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1351     is( keys(%$error) + keys(%$alerts),  0, 'No key for error and alert' . str($error, $question, $alerts) );
1352     is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
1353
1354     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1355     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1356     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1357     is( $error->{USERBLOCKEDOVERDUE},      1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
1358
1359     # Patron cannot issue item_1, they are debarred
1360     my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1361     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->{borrowernumber}, expiration => $tomorrow } );
1362     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1363     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1364     is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
1365
1366     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->{borrowernumber} } );
1367     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1368     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1369     is( $error->{USERBLOCKEDNOENDDATE},    '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
1370 };
1371
1372 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
1373     plan tests => 1;
1374
1375     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1376     my $patron_category_x = $builder->build_object(
1377         {
1378             class => 'Koha::Patron::Categories',
1379             value => { category_type => 'X' }
1380         }
1381     );
1382     my $patron = $builder->build_object(
1383         {
1384             class => 'Koha::Patrons',
1385             value => {
1386                 categorycode  => $patron_category_x->categorycode,
1387                 gonenoaddress => undef,
1388                 lost          => undef,
1389                 debarred      => undef,
1390                 borrowernotes => ""
1391             }
1392         }
1393     );
1394     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1395     my $item_1 = $builder->build(
1396         {
1397             source => 'Item',
1398             value  => {
1399                 homebranch    => $library->branchcode,
1400                 holdingbranch => $library->branchcode,
1401                 notforloan    => 0,
1402                 itemlost      => 0,
1403                 withdrawn     => 0,
1404                 restricted    => 0,
1405                 biblionumber  => $biblioitem_1->{biblionumber}
1406             }
1407         }
1408     );
1409
1410     my ( $error, $question, $alerts ) = CanBookBeIssued( $patron->unblessed, $item_1->{barcode} );
1411     is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
1412
1413     # TODO There are other tests to provide here
1414 };
1415
1416 subtest 'MultipleReserves' => sub {
1417     plan tests => 3;
1418
1419     my $biblio = MARC::Record->new();
1420     my $title = 'Silence in the library';
1421     $biblio->append_fields(
1422         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
1423         MARC::Field->new('245', ' ', ' ', a => $title),
1424     );
1425
1426     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
1427
1428     my $branch = $library2->{branchcode};
1429
1430     my $barcode1 = 'R00110001';
1431     my ( $item_bibnum1, $item_bibitemnum1, $itemnumber1 ) = AddItem(
1432         {
1433             homebranch       => $branch,
1434             holdingbranch    => $branch,
1435             barcode          => $barcode1,
1436             replacementprice => 12.00,
1437             itype            => $itemtype
1438         },
1439         $biblionumber
1440     );
1441
1442     my $barcode2 = 'R00110002';
1443     my ( $item_bibnum2, $item_bibitemnum2, $itemnumber2 ) = AddItem(
1444         {
1445             homebranch       => $branch,
1446             holdingbranch    => $branch,
1447             barcode          => $barcode2,
1448             replacementprice => 12.00,
1449             itype            => $itemtype
1450         },
1451         $biblionumber
1452     );
1453
1454     my $bibitems       = '';
1455     my $priority       = '1';
1456     my $resdate        = undef;
1457     my $expdate        = undef;
1458     my $notes          = '';
1459     my $checkitem      = undef;
1460     my $found          = undef;
1461
1462     my %renewing_borrower_data = (
1463         firstname =>  'John',
1464         surname => 'Renewal',
1465         categorycode => $patron_category->{categorycode},
1466         branchcode => $branch,
1467     );
1468     my $renewing_borrowernumber = AddMember(%renewing_borrower_data);
1469     my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
1470     my $issue = AddIssue( $renewing_borrower, $barcode1);
1471     my $datedue = dt_from_string( $issue->date_due() );
1472     is (defined $issue->date_due(), 1, "item 1 checked out");
1473     my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $itemnumber1 })->borrowernumber;
1474
1475     my %reserving_borrower_data1 = (
1476         firstname =>  'Katrin',
1477         surname => 'Reservation',
1478         categorycode => $patron_category->{categorycode},
1479         branchcode => $branch,
1480     );
1481     my $reserving_borrowernumber1 = AddMember(%reserving_borrower_data1);
1482     AddReserve(
1483         $branch, $reserving_borrowernumber1, $biblionumber,
1484         $bibitems,  $priority, $resdate, $expdate, $notes,
1485         $title, $checkitem, $found
1486     );
1487
1488     my %reserving_borrower_data2 = (
1489         firstname =>  'Kirk',
1490         surname => 'Reservation',
1491         categorycode => $patron_category->{categorycode},
1492         branchcode => $branch,
1493     );
1494     my $reserving_borrowernumber2 = AddMember(%reserving_borrower_data2);
1495     AddReserve(
1496         $branch, $reserving_borrowernumber2, $biblionumber,
1497         $bibitems,  $priority, $resdate, $expdate, $notes,
1498         $title, $checkitem, $found
1499     );
1500
1501     {
1502         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber1, 1);
1503         is($renewokay, 0, 'Bug 17641 - should cover the case where 2 books are both reserved, so failing');
1504     }
1505
1506     my $barcode3 = 'R00110003';
1507     my ( $item_bibnum3, $item_bibitemnum3, $itemnumber3 ) = AddItem(
1508         {
1509             homebranch       => $branch,
1510             holdingbranch    => $branch,
1511             barcode          => $barcode3,
1512             replacementprice => 12.00,
1513             itype            => $itemtype
1514         },
1515         $biblionumber
1516     );
1517
1518     {
1519         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber1, 1);
1520         is($renewokay, 1, 'Bug 17641 - should cover the case where 2 books are reserved, but a third one is available');
1521     }
1522 };
1523
1524 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
1525     plan tests => 5;
1526
1527     my $library = $builder->build( { source => 'Branch' } );
1528     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1529
1530     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1531     my $biblionumber = $biblioitem->{biblionumber};
1532     my $item_1 = $builder->build(
1533         {   source => 'Item',
1534             value  => {
1535                 homebranch    => $library->{branchcode},
1536                 holdingbranch => $library->{branchcode},
1537                 notforloan    => 0,
1538                 itemlost      => 0,
1539                 withdrawn     => 0,
1540                 biblionumber  => $biblionumber,
1541             }
1542         }
1543     );
1544     my $item_2 = $builder->build(
1545         {   source => 'Item',
1546             value  => {
1547                 homebranch    => $library->{branchcode},
1548                 holdingbranch => $library->{branchcode},
1549                 notforloan    => 0,
1550                 itemlost      => 0,
1551                 withdrawn     => 0,
1552                 biblionumber  => $biblionumber,
1553             }
1554         }
1555     );
1556
1557     my ( $error, $question, $alerts );
1558     my $issue = AddIssue( $patron, $item_1->{barcode}, dt_from_string->add( days => 1 ) );
1559
1560     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1561     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1562     is( keys(%$error) + keys(%$alerts),  0, 'No error or alert should be raised' . str($error, $question, $alerts) );
1563     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) );
1564
1565     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1566     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1567     is( keys(%$error) + keys(%$question) + keys(%$alerts),  0, 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1' . str($error, $question, $alerts) );
1568
1569     # Add a subscription
1570     Koha::Subscription->new({ biblionumber => $biblionumber })->store;
1571
1572     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1573     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1574     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) );
1575
1576     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1577     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1578     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) );
1579 };
1580
1581 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
1582     plan tests => 8;
1583
1584     my $library = $builder->build( { source => 'Branch' } );
1585     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1586
1587     # Add 2 items
1588     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1589     my $item_1 = $builder->build(
1590         {
1591             source => 'Item',
1592             value  => {
1593                 homebranch    => $library->{branchcode},
1594                 holdingbranch => $library->{branchcode},
1595                 notforloan    => 0,
1596                 itemlost      => 0,
1597                 withdrawn     => 0,
1598                 biblionumber  => $biblioitem_1->{biblionumber}
1599             }
1600         }
1601     );
1602     my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1603     my $item_2 = $builder->build(
1604         {
1605             source => 'Item',
1606             value  => {
1607                 homebranch    => $library->{branchcode},
1608                 holdingbranch => $library->{branchcode},
1609                 notforloan    => 0,
1610                 itemlost      => 0,
1611                 withdrawn     => 0,
1612                 biblionumber  => $biblioitem_2->{biblionumber}
1613             }
1614         }
1615     );
1616
1617     # And the issuing rule
1618     Koha::IssuingRules->search->delete;
1619     my $rule = Koha::IssuingRule->new(
1620         {
1621             categorycode => '*',
1622             itemtype     => '*',
1623             branchcode   => '*',
1624             maxissueqty  => 99,
1625             issuelength  => 1,
1626             firstremind  => 1,        # 1 day of grace
1627             finedays     => 2,        # 2 days of fine per day of overdue
1628             lengthunit   => 'days',
1629         }
1630     );
1631     $rule->store();
1632
1633     # Patron cannot issue item_1, they have overdues
1634     my $five_days_ago = dt_from_string->subtract( days => 5 );
1635     my $ten_days_ago  = dt_from_string->subtract( days => 10 );
1636     AddIssue( $patron, $item_1->{barcode}, $five_days_ago );    # Add an overdue
1637     AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1638       ;    # Add another overdue
1639
1640     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
1641     AddReturn( $item_1->{barcode}, $library->{branchcode},
1642         undef, undef, dt_from_string );
1643     my $debarments = Koha::Patron::Debarments::GetDebarments(
1644         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1645     is( scalar(@$debarments), 1 );
1646
1647     # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
1648     # Same for the others
1649     my $expected_expiration = output_pref(
1650         {
1651             dt         => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1652             dateformat => 'sql',
1653             dateonly   => 1
1654         }
1655     );
1656     is( $debarments->[0]->{expiration}, $expected_expiration );
1657
1658     AddReturn( $item_2->{barcode}, $library->{branchcode},
1659         undef, undef, dt_from_string );
1660     $debarments = Koha::Patron::Debarments::GetDebarments(
1661         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1662     is( scalar(@$debarments), 1 );
1663     $expected_expiration = output_pref(
1664         {
1665             dt         => dt_from_string->add( days => ( 10 - 1 ) * 2 ),
1666             dateformat => 'sql',
1667             dateonly   => 1
1668         }
1669     );
1670     is( $debarments->[0]->{expiration}, $expected_expiration );
1671
1672     Koha::Patron::Debarments::DelUniqueDebarment(
1673         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1674
1675     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
1676     AddIssue( $patron, $item_1->{barcode}, $five_days_ago );    # Add an overdue
1677     AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1678       ;    # Add another overdue
1679     AddReturn( $item_1->{barcode}, $library->{branchcode},
1680         undef, undef, dt_from_string );
1681     $debarments = Koha::Patron::Debarments::GetDebarments(
1682         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1683     is( scalar(@$debarments), 1 );
1684     $expected_expiration = output_pref(
1685         {
1686             dt         => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1687             dateformat => 'sql',
1688             dateonly   => 1
1689         }
1690     );
1691     is( $debarments->[0]->{expiration}, $expected_expiration );
1692
1693     AddReturn( $item_2->{barcode}, $library->{branchcode},
1694         undef, undef, dt_from_string );
1695     $debarments = Koha::Patron::Debarments::GetDebarments(
1696         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1697     is( scalar(@$debarments), 1 );
1698     $expected_expiration = output_pref(
1699         {
1700             dt => dt_from_string->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
1701             dateformat => 'sql',
1702             dateonly   => 1
1703         }
1704     );
1705     is( $debarments->[0]->{expiration}, $expected_expiration );
1706 };
1707
1708 subtest 'AddReturn | is_overdue' => sub {
1709     plan tests => 5;
1710
1711     t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
1712     t::lib::Mocks::mock_preference('finesMode', 'production');
1713     t::lib::Mocks::mock_preference('MaxFine', '100');
1714
1715     my $library = $builder->build( { source => 'Branch' } );
1716     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1717
1718     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1719     my $item = $builder->build(
1720         {
1721             source => 'Item',
1722             value  => {
1723                 homebranch    => $library->{branchcode},
1724                 holdingbranch => $library->{branchcode},
1725                 notforloan    => 0,
1726                 itemlost      => 0,
1727                 withdrawn     => 0,
1728                 biblionumber  => $biblioitem->{biblionumber},
1729             }
1730         }
1731     );
1732
1733     Koha::IssuingRules->search->delete;
1734     my $rule = Koha::IssuingRule->new(
1735         {
1736             categorycode => '*',
1737             itemtype     => '*',
1738             branchcode   => '*',
1739             maxissueqty  => 99,
1740             issuelength  => 6,
1741             lengthunit   => 'days',
1742             fine         => 1, # Charge 1 every day of overdue
1743             chargeperiod => 1,
1744         }
1745     );
1746     $rule->store();
1747
1748     my $one_day_ago   = dt_from_string->subtract( days => 1 );
1749     my $five_days_ago = dt_from_string->subtract( days => 5 );
1750     my $ten_days_ago  = dt_from_string->subtract( days => 10 );
1751     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1752
1753     # No date specify, today will be used
1754     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1755     AddReturn( $item->{barcode}, $library->{branchcode} );
1756     is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
1757     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1758
1759     # specify return date 5 days before => no overdue
1760     AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
1761     AddReturn( $item->{barcode}, $library->{branchcode}, undef, undef, $ten_days_ago );
1762     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
1763     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1764
1765     # specify return date 5 days later => overdue
1766     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1767     AddReturn( $item->{barcode}, $library->{branchcode}, undef, undef, $five_days_ago );
1768     is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
1769     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1770
1771     # specify dropbox date 5 days before => no overdue
1772     AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
1773     AddReturn( $item->{barcode}, $library->{branchcode}, undef, 1, undef, $ten_days_ago );
1774     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
1775     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1776
1777     # specify dropbox date 5 days later => overdue, or... not
1778     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1779     AddReturn( $item->{barcode}, $library->{branchcode}, undef, 1, undef, $five_days_ago );
1780     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
1781     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1782 };
1783
1784 subtest '_FixAccountForLostAndReturned' => sub {
1785     plan tests => 2;
1786
1787     # Generate test biblio
1788     my $biblio = MARC::Record->new();
1789     my $title  = 'Koha for Dummies';
1790     $biblio->append_fields(
1791         MARC::Field->new( '100', ' ', ' ', a => 'Hall, Daria' ),
1792         MARC::Field->new( '245', ' ', ' ', a => $title ),
1793     );
1794
1795     my ( $biblionumber, $biblioitemnumber ) = AddBiblio( $biblio, '' );
1796
1797     my $barcode = 'KD123456789';
1798     my $branchcode  = $library2->{branchcode};
1799
1800     my ( $item_bibnum, $item_bibitemnum, $itemnumber ) = AddItem(
1801         {
1802             homebranch       => $branchcode,
1803             holdingbranch    => $branchcode,
1804             barcode          => $barcode,
1805             replacementprice => 99.00,
1806             itype            => $itemtype
1807         },
1808         $biblionumber
1809     );
1810
1811     my $patron = $builder->build( { source => 'Borrower' } );
1812
1813     my $accountline = Koha::Account::Line->new(
1814         {
1815             borrowernumber => $patron->{borrowernumber},
1816             accounttype    => 'L',
1817             itemnumber     => $itemnumber,
1818             amount => 99.00,
1819             amountoutstanding => 99.00,
1820         }
1821     )->store();
1822
1823     C4::Circulation::_FixAccountForLostAndReturned( $itemnumber, $patron->{borrowernumber} );
1824
1825     $accountline->_result()->discard_changes();
1826
1827     is( $accountline->amountoutstanding, '0.000000', 'Lost fee has no outstanding amount' );
1828     is( $accountline->accounttype, 'LR', 'Lost fee now has account type of LR ( Lost Returned )');
1829 };
1830
1831 subtest '_FixOverduesOnReturn' => sub {
1832     plan tests => 6;
1833
1834     # Generate test biblio
1835     my $biblio = MARC::Record->new();
1836     my $title  = 'Koha for Dummies';
1837     $biblio->append_fields(
1838         MARC::Field->new( '100', ' ', ' ', a => 'Hall, Kylie' ),
1839         MARC::Field->new( '245', ' ', ' ', a => $title ),
1840     );
1841
1842     my ( $biblionumber, $biblioitemnumber ) = AddBiblio( $biblio, '' );
1843
1844     my $barcode = 'KD987654321';
1845     my $branchcode  = $library2->{branchcode};
1846
1847     my ( $item_bibnum, $item_bibitemnum, $itemnumber ) = AddItem(
1848         {
1849             homebranch       => $branchcode,
1850             holdingbranch    => $branchcode,
1851             barcode          => $barcode,
1852             replacementprice => 99.00,
1853             itype            => $itemtype
1854         },
1855         $biblionumber
1856     );
1857
1858     my $patron = $builder->build( { source => 'Borrower' } );
1859
1860     ## Start with basic call, should just close out the open fine
1861     my $accountline = Koha::Account::Line->new(
1862         {
1863             borrowernumber => $patron->{borrowernumber},
1864             accounttype    => 'FU',
1865             itemnumber     => $itemnumber,
1866             amount => 99.00,
1867             amountoutstanding => 99.00,
1868             lastincrement => 9.00,
1869         }
1870     )->store();
1871
1872     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $itemnumber );
1873
1874     $accountline->_result()->discard_changes();
1875
1876     is( $accountline->amountoutstanding, '99.000000', 'Fine has the same amount outstanding as previously' );
1877     is( $accountline->accounttype, 'F', 'Open fine ( account type FU ) has been closed out ( account type F )');
1878
1879
1880     ## Run again, with exemptfine enabled
1881     $accountline->set(
1882         {
1883             accounttype    => 'FU',
1884             amountoutstanding => 99.00,
1885         }
1886     )->store();
1887
1888     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $itemnumber, 1 );
1889
1890     $accountline->_result()->discard_changes();
1891
1892     is( $accountline->amountoutstanding, '0.000000', 'Fine has been reduced to 0' );
1893     is( $accountline->accounttype, 'FFOR', 'Open fine ( account type FU ) has been set to fine forgiven ( account type FFOR )');
1894
1895     ## Run again, with dropbox mode enabled
1896     $accountline->set(
1897         {
1898             accounttype    => 'FU',
1899             amountoutstanding => 99.00,
1900         }
1901     )->store();
1902
1903     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $itemnumber, 0, 1 );
1904
1905     $accountline->_result()->discard_changes();
1906
1907     is( $accountline->amountoutstanding, '90.000000', 'Fine has been reduced to 90' );
1908     is( $accountline->accounttype, 'F', 'Open fine ( account type FU ) has been closed out ( account type F )');
1909 };
1910
1911 subtest 'Set waiting flag' => sub {
1912     plan tests => 4;
1913
1914     my $library_1 = $builder->build( { source => 'Branch' } );
1915     my $patron_1  = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1916     my $library_2 = $builder->build( { source => 'Branch' } );
1917     my $patron_2  = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1918
1919     my $biblio = $builder->build( { source => 'Biblio' } );
1920     my $biblioitem = $builder->build( { source => 'Biblioitem', value => { biblionumber => $biblio->{biblionumber} } } );
1921
1922     my $item = $builder->build(
1923         {
1924             source => 'Item',
1925             value  => {
1926                 homebranch    => $library_1->{branchcode},
1927                 holdingbranch => $library_1->{branchcode},
1928                 notforloan    => 0,
1929                 itemlost      => 0,
1930                 withdrawn     => 0,
1931                 biblionumber  => $biblioitem->{biblionumber},
1932             }
1933         }
1934     );
1935
1936     set_userenv( $library_2 );
1937     my $reserve_id = AddReserve(
1938         $library_2->{branchcode}, $patron_2->{borrowernumber}, $biblioitem->{biblionumber},
1939         '', 1, undef, undef, '', undef, $item->{itemnumber},
1940     );
1941
1942     set_userenv( $library_1 );
1943     my $do_transfer = 1;
1944     my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
1945     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
1946     my $hold = Koha::Holds->find( $reserve_id );
1947     is( $hold->found, 'T', 'Hold is in transit' );
1948
1949     my ( $status ) = CheckReserves($item->{itemnumber});
1950     is( $status, 'Reserved', 'Hold is not waiting yet');
1951
1952     set_userenv( $library_2 );
1953     $do_transfer = 0;
1954     AddReturn( $item->{barcode}, $library_2->{branchcode} );
1955     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
1956     $hold = Koha::Holds->find( $reserve_id );
1957     is( $hold->found, 'W', 'Hold is waiting' );
1958     ( $status ) = CheckReserves($item->{itemnumber});
1959     is( $status, 'Waiting', 'Now the hold is waiting');
1960 };
1961
1962 subtest 'CanBookBeIssued | is_overdue' => sub {
1963     plan tests => 3;
1964
1965     # Set a simple circ policy
1966     $dbh->do('DELETE FROM issuingrules');
1967     $dbh->do(
1968     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
1969                                     maxissueqty, issuelength, lengthunit,
1970                                     renewalsallowed, renewalperiod,
1971                                     norenewalbefore, auto_renew,
1972                                     fine, chargeperiod)
1973           VALUES (?, ?, ?, ?,
1974                   ?, ?, ?,
1975                   ?, ?,
1976                   ?, ?,
1977                   ?, ?
1978                  )
1979         },
1980         {},
1981         '*',   '*', '*', 25,
1982         1,     14,  'days',
1983         1,     7,
1984         undef, 0,
1985         .10,   1
1986     );
1987
1988     my $five_days_go = output_pref({ dt => dt_from_string->add( days => 5 ), dateonly => 1});
1989     my $ten_days_go  = output_pref({ dt => dt_from_string->add( days => 10), dateonly => 1 });
1990     my $library = $builder->build( { source => 'Branch' } );
1991     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1992
1993     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1994     my $item = $builder->build(
1995         {
1996             source => 'Item',
1997             value  => {
1998                 homebranch    => $library->{branchcode},
1999                 holdingbranch => $library->{branchcode},
2000                 notforloan    => 0,
2001                 itemlost      => 0,
2002                 withdrawn     => 0,
2003                 biblionumber  => $biblioitem->{biblionumber},
2004             }
2005         }
2006     );
2007
2008     my $issue = AddIssue( $patron, $item->{barcode}, $five_days_go ); # date due was 10d ago
2009     my $actualissue = Koha::Checkouts->find( { itemnumber => $item->{itemnumber} } );
2010     is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
2011     my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->{barcode},$ten_days_go, undef, undef, undef);
2012     is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
2013     is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
2014
2015 };
2016
2017 sub set_userenv {
2018     my ( $library ) = @_;
2019     C4::Context->set_userenv(0,0,0,'firstname','surname', $library->{branchcode}, $library->{branchname}, '', '', '');
2020 }
2021
2022 sub str {
2023     my ( $error, $question, $alert ) = @_;
2024     my $s;
2025     $s  = %$error    ? ' (error: '    . join( ' ', keys %$error    ) . ')' : '';
2026     $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
2027     $s .= %$alert    ? ' (alert: '    . join( ' ', keys %$alert    ) . ')' : '';
2028     return $s;
2029 }