Add release notes for Koha 16.05.19
[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 DateTime;
21 use t::lib::Mocks;
22 use C4::Biblio;
23 use C4::Branch;
24 use C4::Items;
25 use C4::Members;
26 use C4::Reserves;
27 use C4::Overdues qw(UpdateFine CalcFine);
28 use Koha::DateUtils;
29 use Koha::Database;
30
31 use t::lib::TestBuilder;
32
33 use Test::More tests => 87;
34
35 BEGIN {
36     use_ok('C4::Circulation');
37 }
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
62 my $CircControl = C4::Context->preference('CircControl');
63 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
64
65 my $item = {
66     homebranch => $library2->{branchcode},
67     holdingbranch => $library2->{branchcode}
68 };
69
70 my $borrower = {
71     branchcode => $library2->{branchcode}
72 };
73
74 # No userenv, PickupLibrary
75 t::lib::Mocks::mock_preference('IndependentBranches', '0');
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', 'S', ? )", undef, $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 => 'S',
265         branchcode => $branch,
266     );
267
268     my %reserving_borrower_data = (
269         firstname =>  'Katrin',
270         surname => 'Reservation',
271         categorycode => 'S',
272         branchcode => $branch,
273     );
274
275     my %hold_waiting_borrower_data = (
276         firstname =>  'Kyle',
277         surname => 'Reservation',
278         categorycode => 'S',
279         branchcode => $branch,
280     );
281
282     my %restricted_borrower_data = (
283         firstname =>  'Alice',
284         surname => 'Reservation',
285         categorycode => 'S',
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     AddRenewal( $renewing_borrower->{borrowernumber}, $itemnumber7, $branch );
476     $fine = $schema->resultset('Accountline')->single( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $itemnumber7 } );
477     is( $fine->accounttype, 'F', 'Fine on renewed item is closed out properly' );
478     $fine->delete();
479
480     t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
481     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber6);
482     is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
483     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber7);
484     is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
485
486
487     $reserveid = C4::Reserves::GetReserveId({ biblionumber => $biblionumber, itemnumber => $itemnumber, borrowernumber => $reserving_borrowernumber});
488     CancelReserve({ reserve_id => $reserveid });
489
490     # Bug 14101
491     # Test automatic renewal before value for "norenewalbefore" in policy is set
492     # In this case automatic renewal is not permitted prior to due date
493     my $barcode4 = '11235813';
494     my ( $item_bibnum4, $item_bibitemnum4, $itemnumber4 ) = AddItem(
495         {
496             homebranch       => $branch,
497             holdingbranch    => $branch,
498             barcode          => $barcode4,
499             replacementprice => 16.00,
500             itype            => $itemtype
501         },
502         $biblionumber
503     );
504
505     $issue = AddIssue( $renewing_borrower, $barcode4, undef, undef, undef, undef, { auto_renew => 1 } );
506     ( $renewokay, $error ) =
507       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
508     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
509     is( $error, 'auto_too_soon',
510         'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
511
512     # Bug 7413
513     # Test premature manual renewal
514     $dbh->do('UPDATE issuingrules SET norenewalbefore = 7');
515
516     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
517     is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
518     is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
519
520     # Bug 14395
521     # Test 'exact time' setting for syspref NoRenewalBeforePrecision
522     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
523     is(
524         GetSoonestRenewDate( $renewing_borrowernumber, $itemnumber ),
525         $datedue->clone->add( days => -7 ),
526         'Bug 14395: Renewals permitted 7 days before due date, as expected'
527     );
528
529     # Bug 14395
530     # Test 'date' setting for syspref NoRenewalBeforePrecision
531     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
532     is(
533         GetSoonestRenewDate( $renewing_borrowernumber, $itemnumber ),
534         $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
535         'Bug 14395: Renewals permitted 7 days before due date, as expected'
536     );
537
538     # Bug 14101
539     # Test premature automatic renewal
540     ( $renewokay, $error ) =
541       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
542     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
543     is( $error, 'auto_too_soon',
544         'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
545     );
546
547     # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
548     # and test automatic renewal again
549     $dbh->do('UPDATE issuingrules SET norenewalbefore = 0');
550     ( $renewokay, $error ) =
551       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
552     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
553     is( $error, 'auto_too_soon',
554         'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
555     );
556
557     # Change policy so that loans can be renewed 99 days prior to the due date
558     # and test automatic renewal again
559     $dbh->do('UPDATE issuingrules SET norenewalbefore = 99');
560     ( $renewokay, $error ) =
561       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
562     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
563     is( $error, 'auto_renew',
564         'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
565     );
566
567     # Too many renewals
568
569     # set policy to forbid renewals
570     $dbh->do('UPDATE issuingrules SET norenewalbefore = NULL, renewalsallowed = 0');
571
572     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
573     is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
574     is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
575
576     # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
577     t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
578     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
579
580     C4::Overdues::UpdateFine(
581         {
582             issue_id       => $issue->id(),
583             itemnumber     => $itemnumber,
584             borrowernumber => $renewing_borrower->{borrowernumber},
585             amount         => 15.00,
586             type           => q{},
587             due            => Koha::DateUtils::output_pref($datedue)
588         }
589     );
590
591     LostItem( $itemnumber, 1 );
592
593     my $item = Koha::Database->new()->schema()->resultset('Item')->find($itemnumber);
594     ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
595
596     my $total_due = $dbh->selectrow_array(
597         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
598         undef, $renewing_borrower->{borrowernumber}
599     );
600
601     ok( $total_due == 12, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
602
603     C4::Context->dbh->do("DELETE FROM accountlines");
604
605     t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
606     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
607
608     C4::Overdues::UpdateFine(
609         {
610             issue_id       => $issue2->id(),
611             itemnumber     => $itemnumber2,
612             borrowernumber => $renewing_borrower->{borrowernumber},
613             amount         => 15.00,
614             type           => q{},
615             due            => Koha::DateUtils::output_pref($datedue)
616         }
617     );
618
619     LostItem( $itemnumber2, 0 );
620
621     my $item2 = Koha::Database->new()->schema()->resultset('Item')->find($itemnumber2);
622     ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
623
624     $total_due = $dbh->selectrow_array(
625         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
626         undef, $renewing_borrower->{borrowernumber}
627     );
628
629     ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
630
631     my $future = dt_from_string();
632     $future->add( days => 7 );
633     my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
634     ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
635
636     # Users cannot renew any item if there is an overdue item
637     t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
638     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber6);
639     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
640     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber7);
641     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
642
643   }
644
645 {
646     # GetUpcomingDueIssues tests
647     my $barcode  = 'R00000342';
648     my $barcode2 = 'R00000343';
649     my $barcode3 = 'R00000344';
650     my $branch   = $library2->{branchcode};
651
652     #Create another record
653     my $biblio2 = MARC::Record->new();
654     my $title2 = 'Something is worng here';
655     $biblio2->append_fields(
656         MARC::Field->new('100', ' ', ' ', a => 'Anonymous'),
657         MARC::Field->new('245', ' ', ' ', a => $title2),
658     );
659     my ($biblionumber2, $biblioitemnumber2) = AddBiblio($biblio2, '');
660
661     #Create third item
662     AddItem(
663         {
664             homebranch       => $branch,
665             holdingbranch    => $branch,
666             barcode          => $barcode3,
667             itype            => $itemtype
668         },
669         $biblionumber2
670     );
671
672     # Create a borrower
673     my %a_borrower_data = (
674         firstname =>  'Fridolyn',
675         surname => 'SOMERS',
676         categorycode => 'S',
677         branchcode => $branch,
678     );
679
680     my $a_borrower_borrowernumber = AddMember(%a_borrower_data);
681     my $a_borrower = GetMember( borrowernumber => $a_borrower_borrowernumber );
682
683     my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
684     my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
685     my $today = DateTime->today(time_zone => C4::Context->tz());
686
687     my $issue = AddIssue( $a_borrower, $barcode, $yesterday );
688     my $datedue = dt_from_string( $issue->date_due() );
689     my $issue2 = AddIssue( $a_borrower, $barcode2, $two_days_ahead );
690     my $datedue2 = dt_from_string( $issue->date_due() );
691
692     my $upcoming_dues;
693
694     # GetUpcomingDueIssues tests
695     for my $i(0..1) {
696         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
697         is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
698     }
699
700     #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
701     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
702     is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
703
704     for my $i(3..5) {
705         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
706         is ( scalar( @$upcoming_dues ), 1,
707             "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
708     }
709
710     # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
711
712     my $issue3 = AddIssue( $a_borrower, $barcode3, $today );
713
714     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
715     is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
716
717     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
718     is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
719
720     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
721     is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
722
723     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 }  );
724     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
725
726     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
727     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
728
729     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
730     is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
731
732 }
733
734 {
735     my $barcode  = '1234567890';
736     my $branch   = $library2->{branchcode};
737
738     my $biblio = MARC::Record->new();
739     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
740
741     #Create third item
742     my ( undef, undef, $itemnumber ) = AddItem(
743         {
744             homebranch       => $branch,
745             holdingbranch    => $branch,
746             barcode          => $barcode,
747             itype            => $itemtype
748         },
749         $biblionumber
750     );
751
752     # Create a borrower
753     my %a_borrower_data = (
754         firstname =>  'Kyle',
755         surname => 'Hall',
756         categorycode => 'S',
757         branchcode => $branch,
758     );
759
760     my $borrowernumber = AddMember(%a_borrower_data);
761
762     my $issue = AddIssue( GetMember( borrowernumber => $borrowernumber ), $barcode );
763     UpdateFine(
764         {
765             issue_id       => $issue->id(),
766             itemnumber     => $itemnumber,
767             borrowernumber => $borrowernumber,
768             amount         => 0,
769             type           => q{}
770         }
771     );
772
773     my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $itemnumber );
774     my $count = $hr->{count};
775
776     is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
777 }
778
779 {
780     $dbh->do('DELETE FROM issues');
781     $dbh->do('DELETE FROM items');
782     $dbh->do('DELETE FROM issuingrules');
783     $dbh->do(
784         q{
785         INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, maxissueqty, issuelength, lengthunit, renewalsallowed, renewalperiod,
786                     norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
787         },
788         {},
789         '*', '*', '*', 25,
790         20,  14,  'days',
791         1,   7,
792         undef,  0,
793         .10, 1
794     );
795     my $biblio = MARC::Record->new();
796     my ( $biblionumber, $biblioitemnumber ) = AddBiblio( $biblio, '' );
797
798     my $barcode1 = '1234';
799     my ( undef, undef, $itemnumber1 ) = AddItem(
800         {
801             homebranch    => $library2->{branchcode},
802             holdingbranch => $library2->{branchcode},
803             barcode       => $barcode1,
804             itype         => $itemtype
805         },
806         $biblionumber
807     );
808     my $barcode2 = '4321';
809     my ( undef, undef, $itemnumber2 ) = AddItem(
810         {
811             homebranch    => $library2->{branchcode},
812             holdingbranch => $library2->{branchcode},
813             barcode       => $barcode2,
814             itype         => $itemtype
815         },
816         $biblionumber
817     );
818
819     my $borrowernumber1 = AddMember(
820         firstname    => 'Kyle',
821         surname      => 'Hall',
822         categorycode => 'S',
823         branchcode   => $library2->{branchcode},
824     );
825     my $borrowernumber2 = AddMember(
826         firstname    => 'Chelsea',
827         surname      => 'Hall',
828         categorycode => 'S',
829         branchcode   => $library2->{branchcode},
830     );
831
832     my $borrower1 = GetMember( borrowernumber => $borrowernumber1 );
833     my $borrower2 = GetMember( borrowernumber => $borrowernumber2 );
834
835     my $issue = AddIssue( $borrower1, $barcode1 );
836
837     my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
838     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
839
840     AddReserve(
841         $library2->{branchcode}, $borrowernumber2, $biblionumber,
842         '',  1, undef, undef, '',
843         undef, undef, undef
844     );
845
846     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
847     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
848     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
849     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
850
851     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
852     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
853     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
854     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
855
856     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
857     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
858     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
859     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
860
861     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
862     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
863     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
864     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
865
866     # Setting item not checked out to be not for loan but holdable
867     ModItem({ notforloan => -1 }, $biblionumber, $itemnumber2);
868
869     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
870     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' );
871 }
872
873 {
874     # Don't allow renewing onsite checkout
875     my $barcode  = 'R00000XXX';
876     my $branch   = $library->{branchcode};
877
878     #Create another record
879     my $biblio = MARC::Record->new();
880     $biblio->append_fields(
881         MARC::Field->new('100', ' ', ' ', a => 'Anonymous'),
882         MARC::Field->new('245', ' ', ' ', a => 'A title'),
883     );
884     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
885
886     my (undef, undef, $itemnumber) = AddItem(
887         {
888             homebranch       => $branch,
889             holdingbranch    => $branch,
890             barcode          => $barcode,
891             itype            => $itemtype
892         },
893         $biblionumber
894     );
895
896     my $borrowernumber = AddMember(
897         firstname =>  'fn',
898         surname => 'dn',
899         categorycode => 'S',
900         branchcode => $branch,
901     );
902
903     my $borrower = GetMember( borrowernumber => $borrowernumber );
904     my $issue = AddIssue( $borrower, $barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
905     my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $itemnumber );
906     is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
907     is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
908 }
909
910 {
911     my $library = $builder->build({ source => 'Branch' });
912
913     my $biblio = MARC::Record->new();
914     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
915
916     my $barcode = 'just a barcode';
917     my ( undef, undef, $itemnumber ) = AddItem(
918         {
919             homebranch       => $library->{branchcode},
920             holdingbranch    => $library->{branchcode},
921             barcode          => $barcode,
922             itype            => $itemtype
923         },
924         $biblionumber,
925     );
926
927     my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode} } } );
928
929     my $issue = AddIssue( GetMember( borrowernumber => $patron->{borrowernumber} ), $barcode );
930     UpdateFine(
931         {
932             issue_id       => $issue->id(),
933             itemnumber     => $itemnumber,
934             borrowernumber => $patron->{borrowernumber},
935             amount         => 1,
936             type           => q{}
937         }
938     );
939     UpdateFine(
940         {
941             issue_id       => $issue->id(),
942             itemnumber     => $itemnumber,
943             borrowernumber => $patron->{borrowernumber},
944             amount         => 2,
945             type           => q{}
946         }
947     );
948     is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
949 }
950
951 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
952     plan tests => 26;
953
954     my $homebranch    = $builder->build( { source => 'Branch' } );
955     my $holdingbranch = $builder->build( { source => 'Branch' } );
956     my $otherbranch   = $builder->build( { source => 'Branch' } );
957     my $patron_1      = $builder->build( { source => 'Borrower' } );
958     my $patron_2      = $builder->build( { source => 'Borrower' } );
959
960     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
961     my $item = $builder->build(
962         {   source => 'Item',
963             value  => {
964                 homebranch    => $homebranch->{branchcode},
965                 holdingbranch => $holdingbranch->{branchcode},
966                 notforloan    => 0,
967                 itemlost      => 0,
968                 withdrawn     => 0,
969                 biblionumber  => $biblioitem->{biblionumber}
970             }
971         }
972     );
973
974     set_userenv($holdingbranch);
975
976     my $issue = AddIssue( $patron_1, $item->{barcode} );
977     is( ref($issue), 'Koha::Schema::Result::Issue' );    # FIXME Should be Koha::Issue
978
979     my ( $error, $question, $alerts );
980
981     # AllowReturnToBranch == anywhere
982     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
983     ## Can be issued from homebranch
984     set_userenv($homebranch);
985     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
986     is( keys(%$error), 0, 'There should not be any errors (impossible)' );
987     is( keys(%$alerts), 0, 'There should not be any alerts' );
988     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
989     ## Can be issued from holdingbranch
990     set_userenv($holdingbranch);
991     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
992     is( keys(%$error), 0, 'There should not be any errors (impossible)' );
993     is( keys(%$alerts), 0, 'There should not be any alerts' );
994     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
995     ## Can be issued from another branch
996     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
997     is( keys(%$error), 0, 'There should not be any errors (impossible)' );
998     is( keys(%$alerts), 0, 'There should not be any alerts' );
999     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
1000
1001     # AllowReturnToBranch == holdingbranch
1002     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1003     ## Cannot be issued from homebranch
1004     set_userenv($homebranch);
1005     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1006     is( keys(%$question) + keys(%$alerts),  0 );
1007     is( exists $error->{RETURN_IMPOSSIBLE}, 1 );
1008     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
1009     ## Can be issued from holdinbranch
1010     set_userenv($holdingbranch);
1011     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1012     is( keys(%$error) + keys(%$alerts),        0 );
1013     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
1014     ## Cannot be issued from another branch
1015     set_userenv($otherbranch);
1016     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1017     is( keys(%$question) + keys(%$alerts),  0 );
1018     is( exists $error->{RETURN_IMPOSSIBLE}, 1 );
1019     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
1020
1021     # AllowReturnToBranch == homebranch
1022     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1023     ## Can be issued from holdinbranch
1024     set_userenv($homebranch);
1025     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1026     is( keys(%$error) + keys(%$alerts),        0 );
1027     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
1028     ## Cannot be issued from holdinbranch
1029     set_userenv($holdingbranch);
1030     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1031     is( keys(%$question) + keys(%$alerts),  0 );
1032     is( exists $error->{RETURN_IMPOSSIBLE}, 1 );
1033     is( $error->{branch_to_return},         $homebranch->{branchcode} );
1034     ## Cannot be issued from holdinbranch
1035     set_userenv($otherbranch);
1036     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1037     is( keys(%$question) + keys(%$alerts),  0 );
1038     is( exists $error->{RETURN_IMPOSSIBLE}, 1 );
1039     is( $error->{branch_to_return},         $homebranch->{branchcode} );
1040
1041     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1042 };
1043
1044 subtest 'AddIssue & AllowReturnToBranch' => sub {
1045     plan tests => 9;
1046
1047     my $homebranch    = $builder->build( { source => 'Branch' } );
1048     my $holdingbranch = $builder->build( { source => 'Branch' } );
1049     my $otherbranch   = $builder->build( { source => 'Branch' } );
1050     my $patron_1      = $builder->build( { source => 'Borrower' } );
1051     my $patron_2      = $builder->build( { source => 'Borrower' } );
1052
1053     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1054     my $item = $builder->build(
1055         {   source => 'Item',
1056             value  => {
1057                 homebranch    => $homebranch->{branchcode},
1058                 holdingbranch => $holdingbranch->{branchcode},
1059                 notforloan    => 0,
1060                 itemlost      => 0,
1061                 withdrawn     => 0,
1062                 restricted    => 0,
1063                 biblionumber  => $biblioitem->{biblionumber}
1064             }
1065         }
1066     );
1067
1068     set_userenv($holdingbranch);
1069
1070     my $ref_issue = 'Koha::Schema::Result::Issue'; # FIXME Should be Koha::Issue
1071     my $issue = AddIssue( $patron_1, $item->{barcode} );
1072
1073     my ( $error, $question, $alerts );
1074
1075     # AllowReturnToBranch == homebranch
1076     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1077     ## Can be issued from homebranch
1078     set_userenv($homebranch);
1079     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1080     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1081     ## Can be issued from holdinbranch
1082     set_userenv($holdingbranch);
1083     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1084     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1085     ## Can be issued from another branch
1086     set_userenv($otherbranch);
1087     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1088     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1089
1090     # AllowReturnToBranch == holdinbranch
1091     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1092     ## Cannot be issued from homebranch
1093     set_userenv($homebranch);
1094     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1095     ## Can be issued from holdingbranch
1096     set_userenv($holdingbranch);
1097     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1098     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1099     ## Cannot be issued from another branch
1100     set_userenv($otherbranch);
1101     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1102
1103     # AllowReturnToBranch == homebranch
1104     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1105     ## Can be issued from homebranch
1106     set_userenv($homebranch);
1107     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1108     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1109     ## Cannot be issued from holdinbranch
1110     set_userenv($holdingbranch);
1111     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1112     ## Cannot be issued from another branch
1113     set_userenv($otherbranch);
1114     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1115     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1116 };
1117
1118
1119 sub set_userenv {
1120     my ( $library ) = @_;
1121     C4::Context->set_userenv(0,0,0,'firstname','surname', $library->{branchcode}, $library->{branchname}, '', '', '');
1122 }
1123
1124 1;