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