Bug 17829: Move GetMember to Koha::Patron
[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 => 96;
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
464     my $passeddatedue1 = AddIssue($renewing_borrower, $barcode7, $five_weeks_ago);
465     is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: " . $passeddatedue1->date_due);
466
467     my ( $fine ) = CalcFine( GetItem(undef, $barcode7), $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
468     C4::Overdues::UpdateFine(
469         {
470             issue_id       => $passeddatedue1->id(),
471             itemnumber     => $itemnumber7,
472             borrowernumber => $renewing_borrower->{borrowernumber},
473             amount         => $fine,
474             type           => 'FU',
475             due            => Koha::DateUtils::output_pref($five_weeks_ago)
476         }
477     );
478     t::lib::Mocks::mock_preference('RenewalLog', 0);
479     my $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
480     my $old_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
481     AddRenewal( $renewing_borrower->{borrowernumber}, $itemnumber7, $branch );
482     my $new_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
483     is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
484
485     t::lib::Mocks::mock_preference('RenewalLog', 1);
486     $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
487     $old_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
488     AddRenewal( $renewing_borrower->{borrowernumber}, $itemnumber7, $branch );
489     $new_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
490     is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
491
492
493     $fine = $schema->resultset('Accountline')->single( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $itemnumber7 } );
494     is( $fine->accounttype, 'F', 'Fine on renewed item is closed out properly' );
495     $fine->delete();
496
497     t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
498     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber6);
499     is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
500     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber7);
501     is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
502
503
504     $reserveid = C4::Reserves::GetReserveId({ biblionumber => $biblionumber, itemnumber => $itemnumber, borrowernumber => $reserving_borrowernumber});
505     CancelReserve({ reserve_id => $reserveid });
506
507     # Bug 14101
508     # Test automatic renewal before value for "norenewalbefore" in policy is set
509     # In this case automatic renewal is not permitted prior to due date
510     my $barcode4 = '11235813';
511     my ( $item_bibnum4, $item_bibitemnum4, $itemnumber4 ) = AddItem(
512         {
513             homebranch       => $branch,
514             holdingbranch    => $branch,
515             barcode          => $barcode4,
516             replacementprice => 16.00,
517             itype            => $itemtype
518         },
519         $biblionumber
520     );
521
522     $issue = AddIssue( $renewing_borrower, $barcode4, undef, undef, undef, undef, { auto_renew => 1 } );
523     ( $renewokay, $error ) =
524       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
525     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
526     is( $error, 'auto_too_soon',
527         'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
528
529     # Bug 7413
530     # Test premature manual renewal
531     $dbh->do('UPDATE issuingrules SET norenewalbefore = 7');
532
533     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
534     is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
535     is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
536
537     # Bug 14395
538     # Test 'exact time' setting for syspref NoRenewalBeforePrecision
539     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
540     is(
541         GetSoonestRenewDate( $renewing_borrowernumber, $itemnumber ),
542         $datedue->clone->add( days => -7 ),
543         'Bug 14395: Renewals permitted 7 days before due date, as expected'
544     );
545
546     # Bug 14395
547     # Test 'date' setting for syspref NoRenewalBeforePrecision
548     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
549     is(
550         GetSoonestRenewDate( $renewing_borrowernumber, $itemnumber ),
551         $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
552         'Bug 14395: Renewals permitted 7 days before due date, as expected'
553     );
554
555     # Bug 14101
556     # Test premature automatic renewal
557     ( $renewokay, $error ) =
558       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
559     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
560     is( $error, 'auto_too_soon',
561         'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
562     );
563
564     # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
565     # and test automatic renewal again
566     $dbh->do('UPDATE issuingrules SET norenewalbefore = 0');
567     ( $renewokay, $error ) =
568       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
569     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
570     is( $error, 'auto_too_soon',
571         'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
572     );
573
574     # Change policy so that loans can be renewed 99 days prior to the due date
575     # and test automatic renewal again
576     $dbh->do('UPDATE issuingrules SET norenewalbefore = 99');
577     ( $renewokay, $error ) =
578       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
579     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
580     is( $error, 'auto_renew',
581         'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
582     );
583
584     subtest "too_late_renewal / no_auto_renewal_after" => sub {
585         plan tests => 14;
586         my $item_to_auto_renew = $builder->build(
587             {   source => 'Item',
588                 value  => {
589                     biblionumber  => $biblionumber,
590                     homebranch    => $branch,
591                     holdingbranch => $branch,
592                 }
593             }
594         );
595
596         my $ten_days_before = dt_from_string->add( days => -10 );
597         my $ten_days_ahead  = dt_from_string->add( days => 10 );
598         AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
599
600         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 9');
601         ( $renewokay, $error ) =
602           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
603         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
604         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
605
606         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 10');
607         ( $renewokay, $error ) =
608           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
609         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
610         is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
611
612         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 11');
613         ( $renewokay, $error ) =
614           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
615         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
616         is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
617
618         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
619         ( $renewokay, $error ) =
620           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
621         is( $renewokay, 0,            'Do not renew, renewal is automatic' );
622         is( $error,     'auto_renew', 'Cannot renew, renew is automatic' );
623
624         $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 ) );
625         ( $renewokay, $error ) =
626           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
627         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
628         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
629
630         $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 ) );
631         ( $renewokay, $error ) =
632           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
633         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
634         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
635
636         $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 ) );
637         ( $renewokay, $error ) =
638           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
639         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
640         is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
641     };
642
643     subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew" => sub {
644         plan tests => 6;
645         my $item_to_auto_renew = $builder->build({
646             source => 'Item',
647             value => {
648                 biblionumber => $biblionumber,
649                 homebranch       => $branch,
650                 holdingbranch    => $branch,
651             }
652         });
653
654         my $ten_days_before = dt_from_string->add( days => -10 );
655         my $ten_days_ahead = dt_from_string->add( days => 10 );
656         AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
657
658         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
659         C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
660         C4::Context->set_preference('OPACFineNoRenewals','10');
661         my $fines_amount = 5;
662         C4::Accounts::manualinvoice( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber}, "Some fines", 'F', $fines_amount );
663         ( $renewokay, $error ) =
664           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
665         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
666         is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
667
668         C4::Accounts::manualinvoice( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber}, "Some fines", 'F', $fines_amount );
669         ( $renewokay, $error ) =
670           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
671         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
672         is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
673
674         C4::Accounts::manualinvoice( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber}, "Some fines", 'F', $fines_amount );
675         ( $renewokay, $error ) =
676           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
677         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
678         is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
679
680         $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
681     };
682
683     subtest "GetLatestAutoRenewDate" => sub {
684         plan tests => 5;
685         my $item_to_auto_renew = $builder->build(
686             {   source => 'Item',
687                 value  => {
688                     biblionumber  => $biblionumber,
689                     homebranch    => $branch,
690                     holdingbranch => $branch,
691                 }
692             }
693         );
694
695         my $ten_days_before = dt_from_string->add( days => -10 );
696         my $ten_days_ahead  = dt_from_string->add( days => 10 );
697         AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
698         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = "", no_auto_renewal_after_hard_limit = NULL');
699         my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
700         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' );
701         my $five_days_before = dt_from_string->add( days => -5 );
702         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 5, no_auto_renewal_after_hard_limit = NULL');
703         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
704         is( $latest_auto_renew_date->truncate( to => 'minute' ),
705             $five_days_before->truncate( to => 'minute' ),
706             'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
707         );
708         my $five_days_ahead = dt_from_string->add( days => 5 );
709         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 15, no_auto_renewal_after_hard_limit = NULL');
710         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
711         is( $latest_auto_renew_date->truncate( to => 'minute' ),
712             $five_days_ahead->truncate( to => 'minute' ),
713             'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
714         );
715         my $two_days_ahead = dt_from_string->add( days => 2 );
716         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = "", no_auto_renewal_after_hard_limit = ?', undef, dt_from_string->add( days => 2 ) );
717         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
718         is( $latest_auto_renew_date->truncate( to => 'day' ),
719             $two_days_ahead->truncate( to => 'day' ),
720             'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
721         );
722         $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 ) );
723         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
724         is( $latest_auto_renew_date->truncate( to => 'day' ),
725             $two_days_ahead->truncate( to => 'day' ),
726             'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
727         );
728
729     };
730
731     # Too many renewals
732
733     # set policy to forbid renewals
734     $dbh->do('UPDATE issuingrules SET norenewalbefore = NULL, renewalsallowed = 0');
735
736     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
737     is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
738     is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
739
740     # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
741     t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
742     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
743
744     C4::Overdues::UpdateFine(
745         {
746             issue_id       => $issue->id(),
747             itemnumber     => $itemnumber,
748             borrowernumber => $renewing_borrower->{borrowernumber},
749             amount         => 15.00,
750             type           => q{},
751             due            => Koha::DateUtils::output_pref($datedue)
752         }
753     );
754
755     LostItem( $itemnumber, 1 );
756
757     my $item = Koha::Database->new()->schema()->resultset('Item')->find($itemnumber);
758     ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
759
760     my $total_due = $dbh->selectrow_array(
761         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
762         undef, $renewing_borrower->{borrowernumber}
763     );
764
765     ok( $total_due == 12, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
766
767     C4::Context->dbh->do("DELETE FROM accountlines");
768
769     t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
770     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
771
772     C4::Overdues::UpdateFine(
773         {
774             issue_id       => $issue2->id(),
775             itemnumber     => $itemnumber2,
776             borrowernumber => $renewing_borrower->{borrowernumber},
777             amount         => 15.00,
778             type           => q{},
779             due            => Koha::DateUtils::output_pref($datedue)
780         }
781     );
782
783     LostItem( $itemnumber2, 0 );
784
785     my $item2 = Koha::Database->new()->schema()->resultset('Item')->find($itemnumber2);
786     ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
787
788     $total_due = $dbh->selectrow_array(
789         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
790         undef, $renewing_borrower->{borrowernumber}
791     );
792
793     ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
794
795     my $future = dt_from_string();
796     $future->add( days => 7 );
797     my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
798     ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
799
800     # Users cannot renew any item if there is an overdue item
801     t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
802     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber6);
803     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
804     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber7);
805     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
806
807   }
808
809 {
810     # GetUpcomingDueIssues tests
811     my $barcode  = 'R00000342';
812     my $barcode2 = 'R00000343';
813     my $barcode3 = 'R00000344';
814     my $branch   = $library2->{branchcode};
815
816     #Create another record
817     my $biblio2 = MARC::Record->new();
818     my $title2 = 'Something is worng here';
819     $biblio2->append_fields(
820         MARC::Field->new('100', ' ', ' ', a => 'Anonymous'),
821         MARC::Field->new('245', ' ', ' ', a => $title2),
822     );
823     my ($biblionumber2, $biblioitemnumber2) = AddBiblio($biblio2, '');
824
825     #Create third item
826     AddItem(
827         {
828             homebranch       => $branch,
829             holdingbranch    => $branch,
830             barcode          => $barcode3,
831             itype            => $itemtype
832         },
833         $biblionumber2
834     );
835
836     # Create a borrower
837     my %a_borrower_data = (
838         firstname =>  'Fridolyn',
839         surname => 'SOMERS',
840         categorycode => $patron_category->{categorycode},
841         branchcode => $branch,
842     );
843
844     my $a_borrower_borrowernumber = AddMember(%a_borrower_data);
845     my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
846
847     my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
848     my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
849     my $today = DateTime->today(time_zone => C4::Context->tz());
850
851     my $issue = AddIssue( $a_borrower, $barcode, $yesterday );
852     my $datedue = dt_from_string( $issue->date_due() );
853     my $issue2 = AddIssue( $a_borrower, $barcode2, $two_days_ahead );
854     my $datedue2 = dt_from_string( $issue->date_due() );
855
856     my $upcoming_dues;
857
858     # GetUpcomingDueIssues tests
859     for my $i(0..1) {
860         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
861         is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
862     }
863
864     #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
865     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
866     is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
867
868     for my $i(3..5) {
869         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
870         is ( scalar( @$upcoming_dues ), 1,
871             "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
872     }
873
874     # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
875
876     my $issue3 = AddIssue( $a_borrower, $barcode3, $today );
877
878     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
879     is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
880
881     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
882     is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
883
884     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
885     is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
886
887     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 }  );
888     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
889
890     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
891     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
892
893     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
894     is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
895
896 }
897
898 {
899     my $barcode  = '1234567890';
900     my $branch   = $library2->{branchcode};
901
902     my $biblio = MARC::Record->new();
903     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
904
905     #Create third item
906     my ( undef, undef, $itemnumber ) = AddItem(
907         {
908             homebranch       => $branch,
909             holdingbranch    => $branch,
910             barcode          => $barcode,
911             itype            => $itemtype
912         },
913         $biblionumber
914     );
915
916     # Create a borrower
917     my %a_borrower_data = (
918         firstname =>  'Kyle',
919         surname => 'Hall',
920         categorycode => $patron_category->{categorycode},
921         branchcode => $branch,
922     );
923
924     my $borrowernumber = AddMember(%a_borrower_data);
925
926     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
927     my $issue = AddIssue( $borrower, $barcode );
928     UpdateFine(
929         {
930             issue_id       => $issue->id(),
931             itemnumber     => $itemnumber,
932             borrowernumber => $borrowernumber,
933             amount         => 0,
934             type           => q{}
935         }
936     );
937
938     my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $itemnumber );
939     my $count = $hr->{count};
940
941     is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
942 }
943
944 {
945     $dbh->do('DELETE FROM issues');
946     $dbh->do('DELETE FROM items');
947     $dbh->do('DELETE FROM issuingrules');
948     $dbh->do(
949         q{
950         INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, maxissueqty, issuelength, lengthunit, renewalsallowed, renewalperiod,
951                     norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
952         },
953         {},
954         '*', '*', '*', 25,
955         20,  14,  'days',
956         1,   7,
957         undef,  0,
958         .10, 1
959     );
960     my $biblio = MARC::Record->new();
961     my ( $biblionumber, $biblioitemnumber ) = AddBiblio( $biblio, '' );
962
963     my $barcode1 = '1234';
964     my ( undef, undef, $itemnumber1 ) = AddItem(
965         {
966             homebranch    => $library2->{branchcode},
967             holdingbranch => $library2->{branchcode},
968             barcode       => $barcode1,
969             itype         => $itemtype
970         },
971         $biblionumber
972     );
973     my $barcode2 = '4321';
974     my ( undef, undef, $itemnumber2 ) = AddItem(
975         {
976             homebranch    => $library2->{branchcode},
977             holdingbranch => $library2->{branchcode},
978             barcode       => $barcode2,
979             itype         => $itemtype
980         },
981         $biblionumber
982     );
983
984     my $borrowernumber1 = AddMember(
985         firstname    => 'Kyle',
986         surname      => 'Hall',
987         categorycode => $patron_category->{categorycode},
988         branchcode   => $library2->{branchcode},
989     );
990     my $borrowernumber2 = AddMember(
991         firstname    => 'Chelsea',
992         surname      => 'Hall',
993         categorycode => $patron_category->{categorycode},
994         branchcode   => $library2->{branchcode},
995     );
996
997     my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
998     my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
999
1000     my $issue = AddIssue( $borrower1, $barcode1 );
1001
1002     my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1003     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1004
1005     AddReserve(
1006         $library2->{branchcode}, $borrowernumber2, $biblionumber,
1007         '',  1, undef, undef, '',
1008         undef, undef, undef
1009     );
1010
1011     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1012     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1013     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1014     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1015
1016     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1017     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1018     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1019     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1020
1021     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1022     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1023     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1024     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1025
1026     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1027     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1028     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1029     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1030
1031     # Setting item not checked out to be not for loan but holdable
1032     ModItem({ notforloan => -1 }, $biblionumber, $itemnumber2);
1033
1034     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1035     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' );
1036 }
1037
1038 {
1039     # Don't allow renewing onsite checkout
1040     my $barcode  = 'R00000XXX';
1041     my $branch   = $library->{branchcode};
1042
1043     #Create another record
1044     my $biblio = MARC::Record->new();
1045     $biblio->append_fields(
1046         MARC::Field->new('100', ' ', ' ', a => 'Anonymous'),
1047         MARC::Field->new('245', ' ', ' ', a => 'A title'),
1048     );
1049     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
1050
1051     my (undef, undef, $itemnumber) = AddItem(
1052         {
1053             homebranch       => $branch,
1054             holdingbranch    => $branch,
1055             barcode          => $barcode,
1056             itype            => $itemtype
1057         },
1058         $biblionumber
1059     );
1060
1061     my $borrowernumber = AddMember(
1062         firstname =>  'fn',
1063         surname => 'dn',
1064         categorycode => $patron_category->{categorycode},
1065         branchcode => $branch,
1066     );
1067
1068     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1069
1070     my $issue = AddIssue( $borrower, $barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1071     my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $itemnumber );
1072     is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1073     is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1074 }
1075
1076 {
1077     my $library = $builder->build({ source => 'Branch' });
1078
1079     my $biblio = MARC::Record->new();
1080     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
1081
1082     my $barcode = 'just a barcode';
1083     my ( undef, undef, $itemnumber ) = AddItem(
1084         {
1085             homebranch       => $library->{branchcode},
1086             holdingbranch    => $library->{branchcode},
1087             barcode          => $barcode,
1088             itype            => $itemtype
1089         },
1090         $biblionumber,
1091     );
1092
1093     my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode} } } );
1094
1095     my $issue = AddIssue( $patron, $barcode );
1096     UpdateFine(
1097         {
1098             issue_id       => $issue->id(),
1099             itemnumber     => $itemnumber,
1100             borrowernumber => $patron->{borrowernumber},
1101             amount         => 1,
1102             type           => q{}
1103         }
1104     );
1105     UpdateFine(
1106         {
1107             issue_id       => $issue->id(),
1108             itemnumber     => $itemnumber,
1109             borrowernumber => $patron->{borrowernumber},
1110             amount         => 2,
1111             type           => q{}
1112         }
1113     );
1114     is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1115 }
1116
1117 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1118     plan tests => 26;
1119
1120     my $homebranch    = $builder->build( { source => 'Branch' } );
1121     my $holdingbranch = $builder->build( { source => 'Branch' } );
1122     my $otherbranch   = $builder->build( { source => 'Branch' } );
1123     my $patron_1      = $builder->build( { source => 'Borrower' } );
1124     my $patron_2      = $builder->build( { source => 'Borrower' } );
1125
1126     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1127     my $item = $builder->build(
1128         {   source => 'Item',
1129             value  => {
1130                 homebranch    => $homebranch->{branchcode},
1131                 holdingbranch => $holdingbranch->{branchcode},
1132                 notforloan    => 0,
1133                 itemlost      => 0,
1134                 withdrawn     => 0,
1135                 restricted    => 0,
1136                 biblionumber  => $biblioitem->{biblionumber}
1137             }
1138         }
1139     );
1140
1141     set_userenv($holdingbranch);
1142
1143     my $issue = AddIssue( $patron_1, $item->{barcode} );
1144     is( ref($issue), 'Koha::Schema::Result::Issue' );    # FIXME Should be Koha::Checkout
1145
1146     my ( $error, $question, $alerts );
1147
1148     # AllowReturnToBranch == anywhere
1149     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1150     ## Can be issued from homebranch
1151     set_userenv($homebranch);
1152     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1153     is( keys(%$error), 0, 'There should not be any errors (impossible)' );
1154     is( keys(%$alerts), 0, 'There should not be any alerts' );
1155     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
1156     ## Can be issued from holdingbranch
1157     set_userenv($holdingbranch);
1158     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1159     is( keys(%$error), 0, 'There should not be any errors (impossible)' );
1160     is( keys(%$alerts), 0, 'There should not be any alerts' );
1161     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
1162     ## Can be issued from another branch
1163     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1164     is( keys(%$error), 0, 'There should not be any errors (impossible)' );
1165     is( keys(%$alerts), 0, 'There should not be any alerts' );
1166     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
1167
1168     # AllowReturnToBranch == holdingbranch
1169     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1170     ## Cannot be issued from homebranch
1171     set_userenv($homebranch);
1172     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1173     is( keys(%$question) + keys(%$alerts),  0 );
1174     is( exists $error->{RETURN_IMPOSSIBLE}, 1 );
1175     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
1176     ## Can be issued from holdinbranch
1177     set_userenv($holdingbranch);
1178     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1179     is( keys(%$error) + keys(%$alerts),        0 );
1180     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
1181     ## Cannot be issued from another branch
1182     set_userenv($otherbranch);
1183     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1184     is( keys(%$question) + keys(%$alerts),  0 );
1185     is( exists $error->{RETURN_IMPOSSIBLE}, 1 );
1186     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
1187
1188     # AllowReturnToBranch == homebranch
1189     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1190     ## Can be issued from holdinbranch
1191     set_userenv($homebranch);
1192     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1193     is( keys(%$error) + keys(%$alerts),        0 );
1194     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
1195     ## Cannot be issued from holdinbranch
1196     set_userenv($holdingbranch);
1197     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1198     is( keys(%$question) + keys(%$alerts),  0 );
1199     is( exists $error->{RETURN_IMPOSSIBLE}, 1 );
1200     is( $error->{branch_to_return},         $homebranch->{branchcode} );
1201     ## Cannot be issued from holdinbranch
1202     set_userenv($otherbranch);
1203     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1204     is( keys(%$question) + keys(%$alerts),  0 );
1205     is( exists $error->{RETURN_IMPOSSIBLE}, 1 );
1206     is( $error->{branch_to_return},         $homebranch->{branchcode} );
1207
1208     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1209 };
1210
1211 subtest 'AddIssue & AllowReturnToBranch' => sub {
1212     plan tests => 9;
1213
1214     my $homebranch    = $builder->build( { source => 'Branch' } );
1215     my $holdingbranch = $builder->build( { source => 'Branch' } );
1216     my $otherbranch   = $builder->build( { source => 'Branch' } );
1217     my $patron_1      = $builder->build( { source => 'Borrower' } );
1218     my $patron_2      = $builder->build( { source => 'Borrower' } );
1219
1220     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1221     my $item = $builder->build(
1222         {   source => 'Item',
1223             value  => {
1224                 homebranch    => $homebranch->{branchcode},
1225                 holdingbranch => $holdingbranch->{branchcode},
1226                 notforloan    => 0,
1227                 itemlost      => 0,
1228                 withdrawn     => 0,
1229                 biblionumber  => $biblioitem->{biblionumber}
1230             }
1231         }
1232     );
1233
1234     set_userenv($holdingbranch);
1235
1236     my $ref_issue = 'Koha::Schema::Result::Issue'; # FIXME Should be Koha::Checkout
1237     my $issue = AddIssue( $patron_1, $item->{barcode} );
1238
1239     my ( $error, $question, $alerts );
1240
1241     # AllowReturnToBranch == homebranch
1242     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1243     ## Can be issued from homebranch
1244     set_userenv($homebranch);
1245     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1246     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1247     ## Can be issued from holdinbranch
1248     set_userenv($holdingbranch);
1249     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1250     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1251     ## Can be issued from another branch
1252     set_userenv($otherbranch);
1253     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1254     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1255
1256     # AllowReturnToBranch == holdinbranch
1257     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1258     ## Cannot be issued from homebranch
1259     set_userenv($homebranch);
1260     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1261     ## Can be issued from holdingbranch
1262     set_userenv($holdingbranch);
1263     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1264     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1265     ## Cannot be issued from another branch
1266     set_userenv($otherbranch);
1267     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1268
1269     # AllowReturnToBranch == homebranch
1270     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1271     ## Can be issued from homebranch
1272     set_userenv($homebranch);
1273     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1274     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1275     ## Cannot be issued from holdinbranch
1276     set_userenv($holdingbranch);
1277     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1278     ## Cannot be issued from another branch
1279     set_userenv($otherbranch);
1280     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1281     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1282 };
1283
1284 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1285     plan tests => 8;
1286
1287     my $library = $builder->build( { source => 'Branch' } );
1288     my $patron  = $builder->build( { source => 'Borrower' } );
1289
1290     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1291     my $item_1 = $builder->build(
1292         {   source => 'Item',
1293             value  => {
1294                 homebranch    => $library->{branchcode},
1295                 holdingbranch => $library->{branchcode},
1296                 notforloan    => 0,
1297                 itemlost      => 0,
1298                 withdrawn     => 0,
1299                 biblionumber  => $biblioitem_1->{biblionumber}
1300             }
1301         }
1302     );
1303     my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1304     my $item_2 = $builder->build(
1305         {   source => 'Item',
1306             value  => {
1307                 homebranch    => $library->{branchcode},
1308                 holdingbranch => $library->{branchcode},
1309                 notforloan    => 0,
1310                 itemlost      => 0,
1311                 withdrawn     => 0,
1312                 biblionumber  => $biblioitem_2->{biblionumber}
1313             }
1314         }
1315     );
1316
1317     my ( $error, $question, $alerts );
1318
1319     # Patron cannot issue item_1, they have overdues
1320     my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1321     my $issue = AddIssue( $patron, $item_1->{barcode}, $yesterday );    # Add an overdue
1322
1323     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1324     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1325     is( keys(%$error) + keys(%$alerts),  0 );
1326     is( $question->{USERBLOCKEDOVERDUE}, 1 );
1327
1328     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1329     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1330     is( keys(%$question) + keys(%$alerts), 0 );
1331     is( $error->{USERBLOCKEDOVERDUE},      1 );
1332
1333     # Patron cannot issue item_1, they are debarred
1334     my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1335     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->{borrowernumber}, expiration => $tomorrow } );
1336     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1337     is( keys(%$question) + keys(%$alerts), 0 );
1338     is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ) );
1339
1340     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->{borrowernumber} } );
1341     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1342     is( keys(%$question) + keys(%$alerts), 0 );
1343     is( $error->{USERBLOCKEDNOENDDATE},    '9999-12-31' );
1344 };
1345
1346 subtest 'MultipleReserves' => sub {
1347     plan tests => 3;
1348
1349     my $biblio = MARC::Record->new();
1350     my $title = 'Silence in the library';
1351     $biblio->append_fields(
1352         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
1353         MARC::Field->new('245', ' ', ' ', a => $title),
1354     );
1355
1356     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
1357
1358     my $branch = $library2->{branchcode};
1359
1360     my $barcode1 = 'R00110001';
1361     my ( $item_bibnum1, $item_bibitemnum1, $itemnumber1 ) = AddItem(
1362         {
1363             homebranch       => $branch,
1364             holdingbranch    => $branch,
1365             barcode          => $barcode1,
1366             replacementprice => 12.00,
1367             itype            => $itemtype
1368         },
1369         $biblionumber
1370     );
1371
1372     my $barcode2 = 'R00110002';
1373     my ( $item_bibnum2, $item_bibitemnum2, $itemnumber2 ) = AddItem(
1374         {
1375             homebranch       => $branch,
1376             holdingbranch    => $branch,
1377             barcode          => $barcode2,
1378             replacementprice => 12.00,
1379             itype            => $itemtype
1380         },
1381         $biblionumber
1382     );
1383
1384     my $bibitems       = '';
1385     my $priority       = '1';
1386     my $resdate        = undef;
1387     my $expdate        = undef;
1388     my $notes          = '';
1389     my $checkitem      = undef;
1390     my $found          = undef;
1391
1392     my %renewing_borrower_data = (
1393         firstname =>  'John',
1394         surname => 'Renewal',
1395         categorycode => $patron_category->{categorycode},
1396         branchcode => $branch,
1397     );
1398     my $renewing_borrowernumber = AddMember(%renewing_borrower_data);
1399     my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
1400     my $issue = AddIssue( $renewing_borrower, $barcode1);
1401     my $datedue = dt_from_string( $issue->date_due() );
1402     is (defined $issue->date_due(), 1, "item 1 checked out");
1403     my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $itemnumber1 })->borrowernumber;
1404
1405     my %reserving_borrower_data1 = (
1406         firstname =>  'Katrin',
1407         surname => 'Reservation',
1408         categorycode => $patron_category->{categorycode},
1409         branchcode => $branch,
1410     );
1411     my $reserving_borrowernumber1 = AddMember(%reserving_borrower_data1);
1412     AddReserve(
1413         $branch, $reserving_borrowernumber1, $biblionumber,
1414         $bibitems,  $priority, $resdate, $expdate, $notes,
1415         $title, $checkitem, $found
1416     );
1417
1418     my %reserving_borrower_data2 = (
1419         firstname =>  'Kirk',
1420         surname => 'Reservation',
1421         categorycode => $patron_category->{categorycode},
1422         branchcode => $branch,
1423     );
1424     my $reserving_borrowernumber2 = AddMember(%reserving_borrower_data2);
1425     AddReserve(
1426         $branch, $reserving_borrowernumber2, $biblionumber,
1427         $bibitems,  $priority, $resdate, $expdate, $notes,
1428         $title, $checkitem, $found
1429     );
1430
1431     {
1432         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber1, 1);
1433         is($renewokay, 0, 'Bug 17641 - should cover the case where 2 books are both reserved, so failing');
1434     }
1435
1436     my $barcode3 = 'R00110003';
1437     my ( $item_bibnum3, $item_bibitemnum3, $itemnumber3 ) = AddItem(
1438         {
1439             homebranch       => $branch,
1440             holdingbranch    => $branch,
1441             barcode          => $barcode3,
1442             replacementprice => 12.00,
1443             itype            => $itemtype
1444         },
1445         $biblionumber
1446     );
1447
1448     {
1449         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber1, 1);
1450         is($renewokay, 1, 'Bug 17641 - should cover the case where 2 books are reserved, but a third one is available');
1451     }
1452 };
1453
1454 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
1455     plan tests => 5;
1456
1457     my $library = $builder->build( { source => 'Branch' } );
1458     my $patron  = $builder->build( { source => 'Borrower' } );
1459
1460     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1461     my $biblionumber = $biblioitem->{biblionumber};
1462     my $item_1 = $builder->build(
1463         {   source => 'Item',
1464             value  => {
1465                 homebranch    => $library->{branchcode},
1466                 holdingbranch => $library->{branchcode},
1467                 notforloan    => 0,
1468                 itemlost      => 0,
1469                 withdrawn     => 0,
1470                 biblionumber  => $biblionumber,
1471             }
1472         }
1473     );
1474     my $item_2 = $builder->build(
1475         {   source => 'Item',
1476             value  => {
1477                 homebranch    => $library->{branchcode},
1478                 holdingbranch => $library->{branchcode},
1479                 notforloan    => 0,
1480                 itemlost      => 0,
1481                 withdrawn     => 0,
1482                 biblionumber  => $biblionumber,
1483             }
1484         }
1485     );
1486
1487     my ( $error, $question, $alerts );
1488     my $issue = AddIssue( $patron, $item_1->{barcode}, dt_from_string->add( days => 1 ) );
1489
1490     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1491     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1492     is( keys(%$error) + keys(%$alerts),  0, 'No error or alert should be raised' );
1493     is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' );
1494
1495     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1496     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1497     is( keys(%$error) + keys(%$question) + keys(%$alerts),  0, 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1' );
1498
1499     # Add a subscription
1500     Koha::Subscription->new({ biblionumber => $biblionumber })->store;
1501
1502     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1503     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1504     is( keys(%$error) + keys(%$question) + keys(%$alerts),  0, 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription' );
1505
1506     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
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
1511 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
1512     plan tests => 8;
1513
1514     my $library = $builder->build( { source => 'Branch' } );
1515     my $patron  = $builder->build( { source => 'Borrower' } );
1516
1517     # Add 2 items
1518     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1519     my $item_1 = $builder->build(
1520         {
1521             source => 'Item',
1522             value  => {
1523                 homebranch    => $library->{branchcode},
1524                 holdingbranch => $library->{branchcode},
1525                 notforloan    => 0,
1526                 itemlost      => 0,
1527                 withdrawn     => 0,
1528                 biblionumber  => $biblioitem_1->{biblionumber}
1529             }
1530         }
1531     );
1532     my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1533     my $item_2 = $builder->build(
1534         {
1535             source => 'Item',
1536             value  => {
1537                 homebranch    => $library->{branchcode},
1538                 holdingbranch => $library->{branchcode},
1539                 notforloan    => 0,
1540                 itemlost      => 0,
1541                 withdrawn     => 0,
1542                 biblionumber  => $biblioitem_2->{biblionumber}
1543             }
1544         }
1545     );
1546
1547     # And the issuing rule
1548     Koha::IssuingRules->search->delete;
1549     my $rule = Koha::IssuingRule->new(
1550         {
1551             categorycode => '*',
1552             itemtype     => '*',
1553             branchcode   => '*',
1554             maxissueqty  => 99,
1555             issuelength  => 1,
1556             firstremind  => 1,        # 1 day of grace
1557             finedays     => 2,        # 2 days of fine per day of overdue
1558             lengthunit   => 'days',
1559         }
1560     );
1561     $rule->store();
1562
1563     # Patron cannot issue item_1, they have overdues
1564     my $five_days_ago = dt_from_string->subtract( days => 5 );
1565     my $ten_days_ago  = dt_from_string->subtract( days => 10 );
1566     AddIssue( $patron, $item_1->{barcode}, $five_days_ago );    # Add an overdue
1567     AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1568       ;    # Add another overdue
1569
1570     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
1571     AddReturn( $item_1->{barcode}, $library->{branchcode},
1572         undef, undef, dt_from_string );
1573     my $debarments = Koha::Patron::Debarments::GetDebarments(
1574         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1575     is( scalar(@$debarments), 1 );
1576
1577     # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
1578     # Same for the others
1579     my $expected_expiration = output_pref(
1580         {
1581             dt         => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1582             dateformat => 'sql',
1583             dateonly   => 1
1584         }
1585     );
1586     is( $debarments->[0]->{expiration}, $expected_expiration );
1587
1588     AddReturn( $item_2->{barcode}, $library->{branchcode},
1589         undef, undef, dt_from_string );
1590     $debarments = Koha::Patron::Debarments::GetDebarments(
1591         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1592     is( scalar(@$debarments), 1 );
1593     $expected_expiration = output_pref(
1594         {
1595             dt         => dt_from_string->add( days => ( 10 - 1 ) * 2 ),
1596             dateformat => 'sql',
1597             dateonly   => 1
1598         }
1599     );
1600     is( $debarments->[0]->{expiration}, $expected_expiration );
1601
1602     Koha::Patron::Debarments::DelUniqueDebarment(
1603         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1604
1605     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
1606     AddIssue( $patron, $item_1->{barcode}, $five_days_ago );    # Add an overdue
1607     AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1608       ;    # Add another overdue
1609     AddReturn( $item_1->{barcode}, $library->{branchcode},
1610         undef, undef, dt_from_string );
1611     $debarments = Koha::Patron::Debarments::GetDebarments(
1612         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1613     is( scalar(@$debarments), 1 );
1614     $expected_expiration = output_pref(
1615         {
1616             dt         => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1617             dateformat => 'sql',
1618             dateonly   => 1
1619         }
1620     );
1621     is( $debarments->[0]->{expiration}, $expected_expiration );
1622
1623     AddReturn( $item_2->{barcode}, $library->{branchcode},
1624         undef, undef, dt_from_string );
1625     $debarments = Koha::Patron::Debarments::GetDebarments(
1626         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1627     is( scalar(@$debarments), 1 );
1628     $expected_expiration = output_pref(
1629         {
1630             dt => dt_from_string->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
1631             dateformat => 'sql',
1632             dateonly   => 1
1633         }
1634     );
1635     is( $debarments->[0]->{expiration}, $expected_expiration );
1636 };
1637
1638 subtest 'AddReturn | is_overdue' => sub {
1639     plan tests => 5;
1640
1641     t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
1642     t::lib::Mocks::mock_preference('finesMode', 'production');
1643     t::lib::Mocks::mock_preference('MaxFine', '100');
1644
1645     my $library = $builder->build( { source => 'Branch' } );
1646     my $patron  = $builder->build( { source => 'Borrower' } );
1647
1648     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1649     my $item = $builder->build(
1650         {
1651             source => 'Item',
1652             value  => {
1653                 homebranch    => $library->{branchcode},
1654                 holdingbranch => $library->{branchcode},
1655                 notforloan    => 0,
1656                 itemlost      => 0,
1657                 withdrawn     => 0,
1658                 biblionumber  => $biblioitem->{biblionumber},
1659             }
1660         }
1661     );
1662
1663     Koha::IssuingRules->search->delete;
1664     my $rule = Koha::IssuingRule->new(
1665         {
1666             categorycode => '*',
1667             itemtype     => '*',
1668             branchcode   => '*',
1669             maxissueqty  => 99,
1670             issuelength  => 6,
1671             lengthunit   => 'days',
1672             fine         => 1, # Charge 1 every day of overdue
1673             chargeperiod => 1,
1674         }
1675     );
1676     $rule->store();
1677
1678     my $one_day_ago   = dt_from_string->subtract( days => 1 );
1679     my $five_days_ago = dt_from_string->subtract( days => 5 );
1680     my $ten_days_ago  = dt_from_string->subtract( days => 10 );
1681     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1682
1683     # No date specify, today will be used
1684     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1685     AddReturn( $item->{barcode}, $library->{branchcode} );
1686     is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
1687     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1688
1689     # specify return date 5 days before => no overdue
1690     AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
1691     AddReturn( $item->{barcode}, $library->{branchcode}, undef, undef, $ten_days_ago );
1692     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
1693     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1694
1695     # specify return date 5 days later => overdue
1696     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1697     AddReturn( $item->{barcode}, $library->{branchcode}, undef, undef, $five_days_ago );
1698     is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
1699     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1700
1701     # specify dropbox date 5 days before => no overdue
1702     AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
1703     AddReturn( $item->{barcode}, $library->{branchcode}, undef, 1, undef, $ten_days_ago );
1704     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
1705     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1706
1707     # specify dropbox date 5 days later => overdue, or... not
1708     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1709     AddReturn( $item->{barcode}, $library->{branchcode}, undef, 1, undef, $five_days_ago );
1710     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
1711     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1712
1713 };
1714
1715 sub set_userenv {
1716     my ( $library ) = @_;
1717     C4::Context->set_userenv(0,0,0,'firstname','surname', $library->{branchcode}, $library->{branchname}, '', '', '');
1718 }
1719
1720 1;