Bug 15581: Add a circ rule to limit the auto renewals given a delay
[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 => 90;
21
22 BEGIN {
23     require_ok('C4::Circulation');
24 }
25
26 use DateTime;
27
28 use t::lib::Mocks;
29 use t::lib::TestBuilder;
30
31 use C4::Circulation;
32 use C4::Biblio;
33 use C4::Items;
34 use C4::Members;
35 use C4::Reserves;
36 use C4::Overdues qw(UpdateFine CalcFine);
37 use Koha::DateUtils;
38 use Koha::Database;
39
40 my $schema = Koha::Database->schema;
41 $schema->storage->txn_begin;
42 my $builder = t::lib::TestBuilder->new;
43 my $dbh = C4::Context->dbh;
44
45 # Start transaction
46 $dbh->{RaiseError} = 1;
47
48 # Start with a clean slate
49 $dbh->do('DELETE FROM issues');
50
51 my $library = $builder->build({
52     source => 'Branch',
53 });
54 my $library2 = $builder->build({
55     source => 'Branch',
56 });
57
58 my $CircControl = C4::Context->preference('CircControl');
59 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
60
61 my $item = {
62     homebranch => $library2->{branchcode},
63     holdingbranch => $library2->{branchcode}
64 };
65
66 my $borrower = {
67     branchcode => $library2->{branchcode}
68 };
69
70 # No userenv, PickupLibrary
71 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
72 is(
73     C4::Context->preference('CircControl'),
74     'PickupLibrary',
75     'CircControl changed to PickupLibrary'
76 );
77 is(
78     C4::Circulation::_GetCircControlBranch($item, $borrower),
79     $item->{$HomeOrHoldingBranch},
80     '_GetCircControlBranch returned item branch (no userenv defined)'
81 );
82
83 # No userenv, PatronLibrary
84 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
85 is(
86     C4::Context->preference('CircControl'),
87     'PatronLibrary',
88     'CircControl changed to PatronLibrary'
89 );
90 is(
91     C4::Circulation::_GetCircControlBranch($item, $borrower),
92     $borrower->{branchcode},
93     '_GetCircControlBranch returned borrower branch'
94 );
95
96 # No userenv, ItemHomeLibrary
97 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
98 is(
99     C4::Context->preference('CircControl'),
100     'ItemHomeLibrary',
101     'CircControl changed to ItemHomeLibrary'
102 );
103 is(
104     $item->{$HomeOrHoldingBranch},
105     C4::Circulation::_GetCircControlBranch($item, $borrower),
106     '_GetCircControlBranch returned item branch'
107 );
108
109 # Now, set a userenv
110 C4::Context->_new_userenv('xxx');
111 C4::Context->set_userenv(0,0,0,'firstname','surname', $library2->{branchcode}, 'Midway Public Library', '', '', '');
112 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
113
114 # Userenv set, PickupLibrary
115 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
116 is(
117     C4::Context->preference('CircControl'),
118     'PickupLibrary',
119     'CircControl changed to PickupLibrary'
120 );
121 is(
122     C4::Circulation::_GetCircControlBranch($item, $borrower),
123     $library2->{branchcode},
124     '_GetCircControlBranch returned current branch'
125 );
126
127 # Userenv set, PatronLibrary
128 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
129 is(
130     C4::Context->preference('CircControl'),
131     'PatronLibrary',
132     'CircControl changed to PatronLibrary'
133 );
134 is(
135     C4::Circulation::_GetCircControlBranch($item, $borrower),
136     $borrower->{branchcode},
137     '_GetCircControlBranch returned borrower branch'
138 );
139
140 # Userenv set, ItemHomeLibrary
141 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
142 is(
143     C4::Context->preference('CircControl'),
144     'ItemHomeLibrary',
145     'CircControl changed to ItemHomeLibrary'
146 );
147 is(
148     C4::Circulation::_GetCircControlBranch($item, $borrower),
149     $item->{$HomeOrHoldingBranch},
150     '_GetCircControlBranch returned item branch'
151 );
152
153 # Reset initial configuration
154 t::lib::Mocks::mock_preference('CircControl', $CircControl);
155 is(
156     C4::Context->preference('CircControl'),
157     $CircControl,
158     'CircControl reset to its initial value'
159 );
160
161 # Set a simple circ policy
162 $dbh->do('DELETE FROM issuingrules');
163 $dbh->do(
164     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
165                                 maxissueqty, issuelength, lengthunit,
166                                 renewalsallowed, renewalperiod,
167                                 norenewalbefore, auto_renew,
168                                 fine, chargeperiod)
169       VALUES (?, ?, ?, ?,
170               ?, ?, ?,
171               ?, ?,
172               ?, ?,
173               ?, ?
174              )
175     },
176     {},
177     '*', '*', '*', 25,
178     20, 14, 'days',
179     1, 7,
180     undef, 0,
181     .10, 1
182 );
183
184 # Test C4::Circulation::ProcessOfflinePayment
185 my $sth = C4::Context->dbh->prepare("SELECT COUNT(*) FROM accountlines WHERE amount = '-123.45' AND accounttype = 'Pay'");
186 $sth->execute();
187 my ( $original_count ) = $sth->fetchrow_array();
188
189 C4::Context->dbh->do("INSERT INTO borrowers ( cardnumber, surname, firstname, categorycode, branchcode ) VALUES ( '99999999999', 'Hall', 'Kyle', 'S', ? )", undef, $library2->{branchcode} );
190
191 C4::Circulation::ProcessOfflinePayment({ cardnumber => '99999999999', amount => '123.45' });
192
193 $sth->execute();
194 my ( $new_count ) = $sth->fetchrow_array();
195
196 ok( $new_count == $original_count  + 1, 'ProcessOfflinePayment makes payment correctly' );
197
198 C4::Context->dbh->do("DELETE FROM accountlines WHERE borrowernumber IN ( SELECT borrowernumber FROM borrowers WHERE cardnumber = '99999999999' )");
199 C4::Context->dbh->do("DELETE FROM borrowers WHERE cardnumber = '99999999999'");
200 C4::Context->dbh->do("DELETE FROM accountlines");
201 {
202 # CanBookBeRenewed tests
203
204     # Generate test biblio
205     my $biblio = MARC::Record->new();
206     my $title = 'Silence in the library';
207     $biblio->append_fields(
208         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
209         MARC::Field->new('245', ' ', ' ', a => $title),
210     );
211
212     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
213
214     my $barcode = 'R00000342';
215     my $branch = $library2->{branchcode};
216
217     my ( $item_bibnum, $item_bibitemnum, $itemnumber ) = AddItem(
218         {
219             homebranch       => $branch,
220             holdingbranch    => $branch,
221             barcode          => $barcode,
222             replacementprice => 12.00
223         },
224         $biblionumber
225     );
226
227     my $barcode2 = 'R00000343';
228     my ( $item_bibnum2, $item_bibitemnum2, $itemnumber2 ) = AddItem(
229         {
230             homebranch       => $branch,
231             holdingbranch    => $branch,
232             barcode          => $barcode2,
233             replacementprice => 23.00
234         },
235         $biblionumber
236     );
237
238     my $barcode3 = 'R00000346';
239     my ( $item_bibnum3, $item_bibitemnum3, $itemnumber3 ) = AddItem(
240         {
241             homebranch       => $branch,
242             holdingbranch    => $branch,
243             barcode          => $barcode3,
244             replacementprice => 23.00
245         },
246         $biblionumber
247     );
248
249
250
251
252     # Create borrowers
253     my %renewing_borrower_data = (
254         firstname =>  'John',
255         surname => 'Renewal',
256         categorycode => 'S',
257         branchcode => $branch,
258     );
259
260     my %reserving_borrower_data = (
261         firstname =>  'Katrin',
262         surname => 'Reservation',
263         categorycode => 'S',
264         branchcode => $branch,
265     );
266
267     my %hold_waiting_borrower_data = (
268         firstname =>  'Kyle',
269         surname => 'Reservation',
270         categorycode => 'S',
271         branchcode => $branch,
272     );
273
274     my %restricted_borrower_data = (
275         firstname =>  'Alice',
276         surname => 'Reservation',
277         categorycode => 'S',
278         debarred => '3228-01-01',
279         branchcode => $branch,
280     );
281
282     my $renewing_borrowernumber = AddMember(%renewing_borrower_data);
283     my $reserving_borrowernumber = AddMember(%reserving_borrower_data);
284     my $hold_waiting_borrowernumber = AddMember(%hold_waiting_borrower_data);
285     my $restricted_borrowernumber = AddMember(%restricted_borrower_data);
286
287     my $renewing_borrower = GetMember( borrowernumber => $renewing_borrowernumber );
288     my $restricted_borrower = GetMember( borrowernumber => $restricted_borrowernumber );
289
290     my $bibitems       = '';
291     my $priority       = '1';
292     my $resdate        = undef;
293     my $expdate        = undef;
294     my $notes          = '';
295     my $checkitem      = undef;
296     my $found          = undef;
297
298     my $issue = AddIssue( $renewing_borrower, $barcode);
299     my $datedue = dt_from_string( $issue->date_due() );
300     is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
301
302     my $issue2 = AddIssue( $renewing_borrower, $barcode2);
303     $datedue = dt_from_string( $issue->date_due() );
304     is (defined $issue2, 1, "Item 2 checked out, due date: " . $issue2->date_due());
305
306
307     my $borrowing_borrowernumber = GetItemIssue($itemnumber)->{borrowernumber};
308     is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
309
310     my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber, 1);
311     is( $renewokay, 1, 'Can renew, no holds for this title or item');
312
313
314     # Biblio-level hold, renewal test
315     AddReserve(
316         $branch, $reserving_borrowernumber, $biblionumber,
317         $bibitems,  $priority, $resdate, $expdate, $notes,
318         $title, $checkitem, $found
319     );
320
321     # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
322     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
323     t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
324     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
325     is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
326     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
327     is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
328
329     # Now let's add an item level hold, we should no longer be able to renew the item
330     my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
331         {
332             borrowernumber => $hold_waiting_borrowernumber,
333             biblionumber   => $biblionumber,
334             itemnumber     => $itemnumber,
335             branchcode     => $branch,
336             priority       => 3,
337         }
338     );
339     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
340     is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
341     $hold->delete();
342
343     # 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
344     # be able to renew these items
345     $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
346         {
347             borrowernumber => $hold_waiting_borrowernumber,
348             biblionumber   => $biblionumber,
349             itemnumber     => $itemnumber3,
350             branchcode     => $branch,
351             priority       => 0,
352             found          => 'W'
353         }
354     );
355     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
356     is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
357     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
358     is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
359     t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
360
361     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
362     is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
363     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
364
365     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
366     is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
367     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
368
369     my $reserveid = C4::Reserves::GetReserveId({ biblionumber => $biblionumber, borrowernumber => $reserving_borrowernumber});
370     my $reserving_borrower = GetMember( borrowernumber => $reserving_borrowernumber );
371     AddIssue($reserving_borrower, $barcode3);
372     my $reserve = $dbh->selectrow_hashref(
373         'SELECT * FROM old_reserves WHERE reserve_id = ?',
374         { Slice => {} },
375         $reserveid
376     );
377     is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
378
379     # Item-level hold, renewal test
380     AddReserve(
381         $branch, $reserving_borrowernumber, $biblionumber,
382         $bibitems,  $priority, $resdate, $expdate, $notes,
383         $title, $itemnumber, $found
384     );
385
386     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber, 1);
387     is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
388     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
389
390     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2, 1);
391     is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
392
393     # Items can't fill hold for reasons
394     ModItem({ notforloan => 1 }, $biblionumber, $itemnumber);
395     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber, 1);
396     is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
397     ModItem({ notforloan => 0, itype => '' }, $biblionumber, $itemnumber,1);
398
399     # FIXME: Add more for itemtype not for loan etc.
400
401     # Restricted users cannot renew when RestrictionBlockRenewing is enabled
402     my $barcode5 = 'R00000347';
403     my ( $item_bibnum5, $item_bibitemnum5, $itemnumber5 ) = AddItem(
404         {
405             homebranch       => $branch,
406             holdingbranch    => $branch,
407             barcode          => $barcode5,
408             replacementprice => 23.00
409         },
410         $biblionumber
411     );
412     my $datedue5 = AddIssue($restricted_borrower, $barcode5);
413     is (defined $datedue5, 1, "Item with date due checked out, due date: $datedue5");
414
415     t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
416     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
417     is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
418     ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrowernumber, $itemnumber5);
419     is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
420
421     # Users cannot renew an overdue item
422     my $barcode6 = 'R00000348';
423     my ( $item_bibnum6, $item_bibitemnum6, $itemnumber6 ) = AddItem(
424         {
425             homebranch       => $branch,
426             holdingbranch    => $branch,
427             barcode          => $barcode6,
428             replacementprice => 23.00
429         },
430         $biblionumber
431     );
432
433     my $barcode7 = 'R00000349';
434     my ( $item_bibnum7, $item_bibitemnum7, $itemnumber7 ) = AddItem(
435         {
436             homebranch       => $branch,
437             holdingbranch    => $branch,
438             barcode          => $barcode7,
439             replacementprice => 23.00
440         },
441         $biblionumber
442     );
443     my $datedue6 = AddIssue( $renewing_borrower, $barcode6);
444     is (defined $datedue6, 1, "Item 2 checked out, due date: $datedue6");
445
446     my $now = dt_from_string();
447     my $five_weeks = DateTime::Duration->new(weeks => 5);
448     my $five_weeks_ago = $now - $five_weeks;
449
450     my $passeddatedue1 = AddIssue($renewing_borrower, $barcode7, $five_weeks_ago);
451     is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: " . $passeddatedue1->date_due);
452
453     my ( $fine ) = CalcFine( GetItem(undef, $barcode7), $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
454     C4::Overdues::UpdateFine(
455         {
456             issue_id       => $passeddatedue1->id(),
457             itemnumber     => $itemnumber7,
458             borrowernumber => $renewing_borrower->{borrowernumber},
459             amount         => $fine,
460             type           => 'FU',
461             due            => Koha::DateUtils::output_pref($five_weeks_ago)
462         }
463     );
464     AddRenewal( $renewing_borrower->{borrowernumber}, $itemnumber7, $branch );
465     $fine = $schema->resultset('Accountline')->single( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $itemnumber7 } );
466     is( $fine->accounttype, 'F', 'Fine on renewed item is closed out properly' );
467     $fine->delete();
468
469     t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
470     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber6);
471     is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
472     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber7);
473     is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
474
475
476     $reserveid = C4::Reserves::GetReserveId({ biblionumber => $biblionumber, itemnumber => $itemnumber, borrowernumber => $reserving_borrowernumber});
477     CancelReserve({ reserve_id => $reserveid });
478
479     # Bug 14101
480     # Test automatic renewal before value for "norenewalbefore" in policy is set
481     # In this case automatic renewal is not permitted prior to due date
482     my $barcode4 = '11235813';
483     my ( $item_bibnum4, $item_bibitemnum4, $itemnumber4 ) = AddItem(
484         {
485             homebranch       => $branch,
486             holdingbranch    => $branch,
487             barcode          => $barcode4,
488             replacementprice => 16.00
489         },
490         $biblionumber
491     );
492
493     $issue = AddIssue( $renewing_borrower, $barcode4, undef, undef, undef, undef, { auto_renew => 1 } );
494     ( $renewokay, $error ) =
495       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
496     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
497     is( $error, 'auto_too_soon',
498         'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
499
500     # Bug 7413
501     # Test premature manual renewal
502     $dbh->do('UPDATE issuingrules SET norenewalbefore = 7');
503
504     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
505     is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
506     is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
507
508     # Bug 14395
509     # Test 'exact time' setting for syspref NoRenewalBeforePrecision
510     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
511     is(
512         GetSoonestRenewDate( $renewing_borrowernumber, $itemnumber ),
513         $datedue->clone->add( days => -7 ),
514         'Bug 14395: Renewals permitted 7 days before due date, as expected'
515     );
516
517     # Bug 14395
518     # Test 'date' setting for syspref NoRenewalBeforePrecision
519     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
520     is(
521         GetSoonestRenewDate( $renewing_borrowernumber, $itemnumber ),
522         $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
523         'Bug 14395: Renewals permitted 7 days before due date, as expected'
524     );
525
526     # Bug 14101
527     # Test premature automatic renewal
528     ( $renewokay, $error ) =
529       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
530     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
531     is( $error, 'auto_too_soon',
532         'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
533     );
534
535     # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
536     # and test automatic renewal again
537     $dbh->do('UPDATE issuingrules SET norenewalbefore = 0');
538     ( $renewokay, $error ) =
539       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
540     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
541     is( $error, 'auto_too_soon',
542         'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
543     );
544
545     # Change policy so that loans can be renewed 99 days prior to the due date
546     # and test automatic renewal again
547     $dbh->do('UPDATE issuingrules SET norenewalbefore = 99');
548     ( $renewokay, $error ) =
549       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
550     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
551     is( $error, 'auto_renew',
552         'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
553     );
554
555     subtest "too_late_renewal / no_auto_renewal_after" => sub {
556         plan tests => 8;
557         my $item_to_auto_renew = $builder->build(
558             {   source => 'Item',
559                 value  => {
560                     biblionumber  => $biblionumber,
561                     homebranch    => $branch,
562                     holdingbranch => $branch,
563                 }
564             }
565         );
566
567         my $ten_days_before = dt_from_string->add( days => -10 );
568         my $ten_days_ahead  = dt_from_string->add( days => 10 );
569         AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
570
571         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 9');
572         ( $renewokay, $error ) =
573           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
574         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
575         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
576
577         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 10');
578         ( $renewokay, $error ) =
579           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
580         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
581         is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
582
583         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 11');
584         ( $renewokay, $error ) =
585           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
586         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
587         is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
588
589         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
590         ( $renewokay, $error ) =
591           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
592         is( $renewokay, 0,            'Do not renew, renewal is automatic' );
593         is( $error,     'auto_renew', 'Cannot renew, renew is automatic' );
594     };
595
596     # Too many renewals
597
598     # set policy to forbid renewals
599     $dbh->do('UPDATE issuingrules SET norenewalbefore = NULL, renewalsallowed = 0');
600
601     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
602     is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
603     is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
604
605     # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
606     t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
607     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
608
609     C4::Overdues::UpdateFine(
610         {
611             issue_id       => $issue->id(),
612             itemnumber     => $itemnumber,
613             borrowernumber => $renewing_borrower->{borrowernumber},
614             amount         => 15.00,
615             type           => q{},
616             due            => Koha::DateUtils::output_pref($datedue)
617         }
618     );
619
620     LostItem( $itemnumber, 1 );
621
622     my $item = Koha::Database->new()->schema()->resultset('Item')->find($itemnumber);
623     ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
624
625     my $total_due = $dbh->selectrow_array(
626         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
627         undef, $renewing_borrower->{borrowernumber}
628     );
629
630     ok( $total_due == 12, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
631
632     C4::Context->dbh->do("DELETE FROM accountlines");
633
634     t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
635     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
636
637     C4::Overdues::UpdateFine(
638         {
639             issue_id       => $issue2->id(),
640             itemnumber     => $itemnumber2,
641             borrowernumber => $renewing_borrower->{borrowernumber},
642             amount         => 15.00,
643             type           => q{},
644             due            => Koha::DateUtils::output_pref($datedue)
645         }
646     );
647
648     LostItem( $itemnumber2, 0 );
649
650     my $item2 = Koha::Database->new()->schema()->resultset('Item')->find($itemnumber2);
651     ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
652
653     $total_due = $dbh->selectrow_array(
654         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
655         undef, $renewing_borrower->{borrowernumber}
656     );
657
658     ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
659
660     my $future = dt_from_string();
661     $future->add( days => 7 );
662     my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
663     ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
664
665     # Users cannot renew any item if there is an overdue item
666     t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
667     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber6);
668     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
669     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber7);
670     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
671
672   }
673
674 {
675     # GetUpcomingDueIssues tests
676     my $barcode  = 'R00000342';
677     my $barcode2 = 'R00000343';
678     my $barcode3 = 'R00000344';
679     my $branch   = $library2->{branchcode};
680
681     #Create another record
682     my $biblio2 = MARC::Record->new();
683     my $title2 = 'Something is worng here';
684     $biblio2->append_fields(
685         MARC::Field->new('100', ' ', ' ', a => 'Anonymous'),
686         MARC::Field->new('245', ' ', ' ', a => $title2),
687     );
688     my ($biblionumber2, $biblioitemnumber2) = AddBiblio($biblio2, '');
689
690     #Create third item
691     AddItem(
692         {
693             homebranch       => $branch,
694             holdingbranch    => $branch,
695             barcode          => $barcode3
696         },
697         $biblionumber2
698     );
699
700     # Create a borrower
701     my %a_borrower_data = (
702         firstname =>  'Fridolyn',
703         surname => 'SOMERS',
704         categorycode => 'S',
705         branchcode => $branch,
706     );
707
708     my $a_borrower_borrowernumber = AddMember(%a_borrower_data);
709     my $a_borrower = GetMember( borrowernumber => $a_borrower_borrowernumber );
710
711     my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
712     my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
713     my $today = DateTime->today(time_zone => C4::Context->tz());
714
715     my $issue = AddIssue( $a_borrower, $barcode, $yesterday );
716     my $datedue = dt_from_string( $issue->date_due() );
717     my $issue2 = AddIssue( $a_borrower, $barcode2, $two_days_ahead );
718     my $datedue2 = dt_from_string( $issue->date_due() );
719
720     my $upcoming_dues;
721
722     # GetUpcomingDueIssues tests
723     for my $i(0..1) {
724         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
725         is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
726     }
727
728     #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
729     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
730     is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
731
732     for my $i(3..5) {
733         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
734         is ( scalar( @$upcoming_dues ), 1,
735             "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
736     }
737
738     # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
739
740     my $issue3 = AddIssue( $a_borrower, $barcode3, $today );
741
742     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
743     is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
744
745     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
746     is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
747
748     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
749     is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
750
751     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 }  );
752     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
753
754     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
755     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
756
757     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
758     is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
759
760 }
761
762 {
763     my $barcode  = '1234567890';
764     my $branch   = $library2->{branchcode};
765
766     my $biblio = MARC::Record->new();
767     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
768
769     #Create third item
770     my ( undef, undef, $itemnumber ) = AddItem(
771         {
772             homebranch       => $branch,
773             holdingbranch    => $branch,
774             barcode          => $barcode
775         },
776         $biblionumber
777     );
778
779     # Create a borrower
780     my %a_borrower_data = (
781         firstname =>  'Kyle',
782         surname => 'Hall',
783         categorycode => 'S',
784         branchcode => $branch,
785     );
786
787     my $borrowernumber = AddMember(%a_borrower_data);
788
789     my $issue = AddIssue( GetMember( borrowernumber => $borrowernumber ), $barcode );
790     UpdateFine(
791         {
792             issue_id       => $issue->id(),
793             itemnumber     => $itemnumber,
794             borrowernumber => $borrowernumber,
795             amount         => 0
796         }
797     );
798
799     my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $itemnumber );
800     my $count = $hr->{count};
801
802     is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
803 }
804
805 {
806     $dbh->do('DELETE FROM issues');
807     $dbh->do('DELETE FROM items');
808     $dbh->do('DELETE FROM issuingrules');
809     $dbh->do(
810         q{
811         INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, maxissueqty, issuelength, lengthunit, renewalsallowed, renewalperiod,
812                     norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
813         },
814         {},
815         '*', '*', '*', 25,
816         20,  14,  'days',
817         1,   7,
818         undef,  0,
819         .10, 1
820     );
821     my $biblio = MARC::Record->new();
822     my ( $biblionumber, $biblioitemnumber ) = AddBiblio( $biblio, '' );
823
824     my $barcode1 = '1234';
825     my ( undef, undef, $itemnumber1 ) = AddItem(
826         {
827             homebranch    => $library2->{branchcode},
828             holdingbranch => $library2->{branchcode},
829             barcode       => $barcode1,
830         },
831         $biblionumber
832     );
833     my $barcode2 = '4321';
834     my ( undef, undef, $itemnumber2 ) = AddItem(
835         {
836             homebranch    => $library2->{branchcode},
837             holdingbranch => $library2->{branchcode},
838             barcode       => $barcode2,
839         },
840         $biblionumber
841     );
842
843     my $borrowernumber1 = AddMember(
844         firstname    => 'Kyle',
845         surname      => 'Hall',
846         categorycode => 'S',
847         branchcode   => $library2->{branchcode},
848     );
849     my $borrowernumber2 = AddMember(
850         firstname    => 'Chelsea',
851         surname      => 'Hall',
852         categorycode => 'S',
853         branchcode   => $library2->{branchcode},
854     );
855
856     my $borrower1 = GetMember( borrowernumber => $borrowernumber1 );
857     my $borrower2 = GetMember( borrowernumber => $borrowernumber2 );
858
859     my $issue = AddIssue( $borrower1, $barcode1 );
860
861     my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
862     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
863
864     AddReserve(
865         $library2->{branchcode}, $borrowernumber2, $biblionumber,
866         '',  1, undef, undef, '',
867         undef, undef, undef
868     );
869
870     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
871     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
872     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
873     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
874
875     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
876     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
877     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
878     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
879
880     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
881     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
882     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
883     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
884
885     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
886     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
887     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
888     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
889
890     # Setting item not checked out to be not for loan but holdable
891     ModItem({ notforloan => -1 }, $biblionumber, $itemnumber2);
892
893     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
894     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' );
895 }
896
897 {
898     # Don't allow renewing onsite checkout
899     my $barcode  = 'R00000XXX';
900     my $branch   = $library->{branchcode};
901
902     #Create another record
903     my $biblio = MARC::Record->new();
904     $biblio->append_fields(
905         MARC::Field->new('100', ' ', ' ', a => 'Anonymous'),
906         MARC::Field->new('245', ' ', ' ', a => 'A title'),
907     );
908     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
909
910     my (undef, undef, $itemnumber) = AddItem(
911         {
912             homebranch       => $branch,
913             holdingbranch    => $branch,
914             barcode          => $barcode,
915         },
916         $biblionumber
917     );
918
919     my $borrowernumber = AddMember(
920         firstname =>  'fn',
921         surname => 'dn',
922         categorycode => 'S',
923         branchcode => $branch,
924     );
925
926     my $borrower = GetMember( borrowernumber => $borrowernumber );
927     my $issue = AddIssue( $borrower, $barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
928     my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $itemnumber );
929     is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
930     is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
931 }
932
933 {
934     my $library = $builder->build({ source => 'Branch' });
935
936     my $biblio = MARC::Record->new();
937     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
938
939     my $barcode = 'just a barcode';
940     my ( undef, undef, $itemnumber ) = AddItem(
941         {
942             homebranch       => $library->{branchcode},
943             holdingbranch    => $library->{branchcode},
944             barcode          => $barcode,
945         },
946         $biblionumber,
947     );
948
949     my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode} } } );
950
951     my $issue = AddIssue( GetMember( borrowernumber => $patron->{borrowernumber} ), $barcode );
952     UpdateFine(
953         {
954             issue_id       => $issue->id(),
955             itemnumber     => $itemnumber,
956             borrowernumber => $patron->{borrowernumber},
957             amount         => 1,
958         }
959     );
960     UpdateFine(
961         {
962             issue_id       => $issue->id(),
963             itemnumber     => $itemnumber,
964             borrowernumber => $patron->{borrowernumber},
965             amount         => 2,
966         }
967     );
968     is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
969 }
970
971 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
972     plan tests => 23;
973
974     my $homebranch    = $builder->build( { source => 'Branch' } );
975     my $holdingbranch = $builder->build( { source => 'Branch' } );
976     my $otherbranch   = $builder->build( { source => 'Branch' } );
977     my $patron_1      = $builder->build( { source => 'Borrower' } );
978     my $patron_2      = $builder->build( { source => 'Borrower' } );
979
980     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
981     my $item = $builder->build(
982         {   source => 'Item',
983             value  => {
984                 homebranch    => $homebranch->{branchcode},
985                 holdingbranch => $holdingbranch->{branchcode},
986                 notforloan    => 0,
987                 itemlost      => 0,
988                 withdrawn     => 0,
989                 biblionumber  => $biblioitem->{biblionumber}
990             }
991         }
992     );
993
994     set_userenv($holdingbranch);
995
996     my $issue = AddIssue( $patron_1, $item->{barcode} );
997     is( ref($issue), 'Koha::Schema::Result::Issue' );    # FIXME Should be Koha::Issue
998
999     my ( $error, $question, $alerts );
1000
1001     # AllowReturnToBranch == anywhere
1002     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1003     ## Can be issued from homebranch
1004     set_userenv($homebranch);
1005     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1006     is( keys(%$error) + keys(%$alerts),        0 );
1007     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
1008     ## Can be issued from holdingbranch
1009     set_userenv($holdingbranch);
1010     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1011     is( keys(%$error) + keys(%$alerts),        0 );
1012     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
1013     ## Can be issued from another branch
1014     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1015     is( keys(%$error) + keys(%$alerts),        0 );
1016     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
1017
1018     # AllowReturnToBranch == holdingbranch
1019     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1020     ## Cannot be issued from homebranch
1021     set_userenv($homebranch);
1022     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1023     is( keys(%$question) + keys(%$alerts),  0 );
1024     is( exists $error->{RETURN_IMPOSSIBLE}, 1 );
1025     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
1026     ## Can be issued from holdinbranch
1027     set_userenv($holdingbranch);
1028     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1029     is( keys(%$error) + keys(%$alerts),        0 );
1030     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
1031     ## Cannot be issued from another branch
1032     set_userenv($otherbranch);
1033     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1034     is( keys(%$question) + keys(%$alerts),  0 );
1035     is( exists $error->{RETURN_IMPOSSIBLE}, 1 );
1036     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
1037
1038     # AllowReturnToBranch == homebranch
1039     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1040     ## Can be issued from holdinbranch
1041     set_userenv($homebranch);
1042     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1043     is( keys(%$error) + keys(%$alerts),        0 );
1044     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
1045     ## Cannot be issued from holdinbranch
1046     set_userenv($holdingbranch);
1047     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1048     is( keys(%$question) + keys(%$alerts),  0 );
1049     is( exists $error->{RETURN_IMPOSSIBLE}, 1 );
1050     is( $error->{branch_to_return},         $homebranch->{branchcode} );
1051     ## Cannot be issued from holdinbranch
1052     set_userenv($otherbranch);
1053     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1054     is( keys(%$question) + keys(%$alerts),  0 );
1055     is( exists $error->{RETURN_IMPOSSIBLE}, 1 );
1056     is( $error->{branch_to_return},         $homebranch->{branchcode} );
1057
1058     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1059 };
1060
1061 subtest 'AddIssue & AllowReturnToBranch' => sub {
1062     plan tests => 9;
1063
1064     my $homebranch    = $builder->build( { source => 'Branch' } );
1065     my $holdingbranch = $builder->build( { source => 'Branch' } );
1066     my $otherbranch   = $builder->build( { source => 'Branch' } );
1067     my $patron_1      = $builder->build( { source => 'Borrower' } );
1068     my $patron_2      = $builder->build( { source => 'Borrower' } );
1069
1070     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1071     my $item = $builder->build(
1072         {   source => 'Item',
1073             value  => {
1074                 homebranch    => $homebranch->{branchcode},
1075                 holdingbranch => $holdingbranch->{branchcode},
1076                 notforloan    => 0,
1077                 itemlost      => 0,
1078                 withdrawn     => 0,
1079                 biblionumber  => $biblioitem->{biblionumber}
1080             }
1081         }
1082     );
1083
1084     set_userenv($holdingbranch);
1085
1086     my $ref_issue = 'Koha::Schema::Result::Issue'; # FIXME Should be Koha::Issue
1087     my $issue = AddIssue( $patron_1, $item->{barcode} );
1088
1089     my ( $error, $question, $alerts );
1090
1091     # AllowReturnToBranch == homebranch
1092     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1093     ## Can be issued from homebranch
1094     set_userenv($homebranch);
1095     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1096     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1097     ## Can be issued from holdinbranch
1098     set_userenv($holdingbranch);
1099     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1100     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1101     ## Can be issued from another branch
1102     set_userenv($otherbranch);
1103     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1104     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1105
1106     # AllowReturnToBranch == holdinbranch
1107     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1108     ## Cannot be issued from homebranch
1109     set_userenv($homebranch);
1110     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1111     ## Can be issued from holdingbranch
1112     set_userenv($holdingbranch);
1113     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1114     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1115     ## Cannot be issued from another branch
1116     set_userenv($otherbranch);
1117     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1118
1119     # AllowReturnToBranch == homebranch
1120     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1121     ## Can be issued from homebranch
1122     set_userenv($homebranch);
1123     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1124     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1125     ## Cannot be issued from holdinbranch
1126     set_userenv($holdingbranch);
1127     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1128     ## Cannot be issued from another branch
1129     set_userenv($otherbranch);
1130     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1131     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1132 };
1133
1134 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1135     plan tests => 8;
1136
1137     my $library = $builder->build( { source => 'Branch' } );
1138     my $patron  = $builder->build( { source => 'Borrower' } );
1139
1140     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1141     my $item_1 = $builder->build(
1142         {   source => 'Item',
1143             value  => {
1144                 homebranch    => $library->{branchcode},
1145                 holdingbranch => $library->{branchcode},
1146                 notforloan    => 0,
1147                 itemlost      => 0,
1148                 withdrawn     => 0,
1149                 biblionumber  => $biblioitem_1->{biblionumber}
1150             }
1151         }
1152     );
1153     my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1154     my $item_2 = $builder->build(
1155         {   source => 'Item',
1156             value  => {
1157                 homebranch    => $library->{branchcode},
1158                 holdingbranch => $library->{branchcode},
1159                 notforloan    => 0,
1160                 itemlost      => 0,
1161                 withdrawn     => 0,
1162                 biblionumber  => $biblioitem_2->{biblionumber}
1163             }
1164         }
1165     );
1166
1167     my ( $error, $question, $alerts );
1168
1169     # Patron cannot issue item_1, he has overdues
1170     my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1171     my $issue = AddIssue( $patron, $item_1->{barcode}, $yesterday );    # Add an overdue
1172
1173     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1174     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1175     is( keys(%$error) + keys(%$alerts),  0 );
1176     is( $question->{USERBLOCKEDOVERDUE}, 1 );
1177
1178     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1179     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1180     is( keys(%$question) + keys(%$alerts), 0 );
1181     is( $error->{USERBLOCKEDOVERDUE},      1 );
1182
1183     # Patron cannot issue item_1, he is debarred
1184     my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1185     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->{borrowernumber}, expiration => $tomorrow } );
1186     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1187     is( keys(%$question) + keys(%$alerts), 0 );
1188     is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ) );
1189
1190     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->{borrowernumber} } );
1191     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1192     is( keys(%$question) + keys(%$alerts), 0 );
1193     is( $error->{USERBLOCKEDNOENDDATE},    '9999-12-31' );
1194 };
1195
1196 sub set_userenv {
1197     my ( $library ) = @_;
1198     C4::Context->set_userenv(0,0,0,'firstname','surname', $library->{branchcode}, $library->{branchname}, '', '', '');
1199 }
1200
1201 1;