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