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