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