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