Bug 17575: Remove itemtype-related warnings from Circulation.t
[koha.git] / t / db_dependent / Circulation.t
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19
20 use Test::More tests => 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 my $itemtype = $builder->build(
58     {   source => 'Itemtype',
59         value  => { notforloan => undef, rentalcharge => 0 }
60     }
61 )->{itemtype};
62
63 my $CircControl = C4::Context->preference('CircControl');
64 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
65
66 my $item = {
67     homebranch => $library2->{branchcode},
68     holdingbranch => $library2->{branchcode}
69 };
70
71 my $borrower = {
72     branchcode => $library2->{branchcode}
73 };
74
75 # No userenv, PickupLibrary
76 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
77 is(
78     C4::Context->preference('CircControl'),
79     'PickupLibrary',
80     'CircControl changed to PickupLibrary'
81 );
82 is(
83     C4::Circulation::_GetCircControlBranch($item, $borrower),
84     $item->{$HomeOrHoldingBranch},
85     '_GetCircControlBranch returned item branch (no userenv defined)'
86 );
87
88 # No userenv, PatronLibrary
89 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
90 is(
91     C4::Context->preference('CircControl'),
92     'PatronLibrary',
93     'CircControl changed to PatronLibrary'
94 );
95 is(
96     C4::Circulation::_GetCircControlBranch($item, $borrower),
97     $borrower->{branchcode},
98     '_GetCircControlBranch returned borrower branch'
99 );
100
101 # No userenv, ItemHomeLibrary
102 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
103 is(
104     C4::Context->preference('CircControl'),
105     'ItemHomeLibrary',
106     'CircControl changed to ItemHomeLibrary'
107 );
108 is(
109     $item->{$HomeOrHoldingBranch},
110     C4::Circulation::_GetCircControlBranch($item, $borrower),
111     '_GetCircControlBranch returned item branch'
112 );
113
114 # Now, set a userenv
115 C4::Context->_new_userenv('xxx');
116 C4::Context->set_userenv(0,0,0,'firstname','surname', $library2->{branchcode}, 'Midway Public Library', '', '', '');
117 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
118
119 # Userenv set, PickupLibrary
120 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
121 is(
122     C4::Context->preference('CircControl'),
123     'PickupLibrary',
124     'CircControl changed to PickupLibrary'
125 );
126 is(
127     C4::Circulation::_GetCircControlBranch($item, $borrower),
128     $library2->{branchcode},
129     '_GetCircControlBranch returned current branch'
130 );
131
132 # Userenv set, PatronLibrary
133 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
134 is(
135     C4::Context->preference('CircControl'),
136     'PatronLibrary',
137     'CircControl changed to PatronLibrary'
138 );
139 is(
140     C4::Circulation::_GetCircControlBranch($item, $borrower),
141     $borrower->{branchcode},
142     '_GetCircControlBranch returned borrower branch'
143 );
144
145 # Userenv set, ItemHomeLibrary
146 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
147 is(
148     C4::Context->preference('CircControl'),
149     'ItemHomeLibrary',
150     'CircControl changed to ItemHomeLibrary'
151 );
152 is(
153     C4::Circulation::_GetCircControlBranch($item, $borrower),
154     $item->{$HomeOrHoldingBranch},
155     '_GetCircControlBranch returned item branch'
156 );
157
158 # Reset initial configuration
159 t::lib::Mocks::mock_preference('CircControl', $CircControl);
160 is(
161     C4::Context->preference('CircControl'),
162     $CircControl,
163     'CircControl reset to its initial value'
164 );
165
166 # Set a simple circ policy
167 $dbh->do('DELETE FROM issuingrules');
168 $dbh->do(
169     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
170                                 maxissueqty, issuelength, lengthunit,
171                                 renewalsallowed, renewalperiod,
172                                 norenewalbefore, auto_renew,
173                                 fine, chargeperiod)
174       VALUES (?, ?, ?, ?,
175               ?, ?, ?,
176               ?, ?,
177               ?, ?,
178               ?, ?
179              )
180     },
181     {},
182     '*', '*', '*', 25,
183     20, 14, 'days',
184     1, 7,
185     undef, 0,
186     .10, 1
187 );
188
189 # Test C4::Circulation::ProcessOfflinePayment
190 my $sth = C4::Context->dbh->prepare("SELECT COUNT(*) FROM accountlines WHERE amount = '-123.45' AND accounttype = 'Pay'");
191 $sth->execute();
192 my ( $original_count ) = $sth->fetchrow_array();
193
194 C4::Context->dbh->do("INSERT INTO borrowers ( cardnumber, surname, firstname, categorycode, branchcode ) VALUES ( '99999999999', 'Hall', 'Kyle', '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     subtest "too_late_renewal / no_auto_renewal_after" => sub {
568         plan tests => 8;
569         my $item_to_auto_renew = $builder->build(
570             {   source => 'Item',
571                 value  => {
572                     biblionumber  => $biblionumber,
573                     homebranch    => $branch,
574                     holdingbranch => $branch,
575                 }
576             }
577         );
578
579         my $ten_days_before = dt_from_string->add( days => -10 );
580         my $ten_days_ahead  = dt_from_string->add( days => 10 );
581         AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
582
583         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 9');
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_late', 'Cannot renew, too late(returned code is auto_too_late)' );
588
589         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 10');
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_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
594
595         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 11');
596         ( $renewokay, $error ) =
597           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
598         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
599         is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
600
601         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
602         ( $renewokay, $error ) =
603           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
604         is( $renewokay, 0,            'Do not renew, renewal is automatic' );
605         is( $error,     'auto_renew', 'Cannot renew, renew is automatic' );
606     };
607
608     subtest "GetLatestAutoRenewDate" => sub {
609         plan tests => 3;
610         my $item_to_auto_renew = $builder->build(
611             {   source => 'Item',
612                 value  => {
613                     biblionumber  => $biblionumber,
614                     homebranch    => $branch,
615                     holdingbranch => $branch,
616                 }
617             }
618         );
619
620         my $ten_days_before = dt_from_string->add( days => -10 );
621         my $ten_days_ahead  = dt_from_string->add( days => 10 );
622         AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
623         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = ""');
624         my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
625         is( $latest_auto_renew_date, undef, 'GetLatestAutoRenewDate should return undef if no_auto_renewal_after is not defined' );
626         my $five_days_before = dt_from_string->add( days => -5 );
627         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 5');
628         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
629         is( $latest_auto_renew_date->truncate( to => 'minute' ),
630             $five_days_before->truncate( to => 'minute' ),
631             'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
632         );
633         my $five_days_ahead = dt_from_string->add( days => 5 );
634         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 15');
635         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
636         is( $latest_auto_renew_date->truncate( to => 'minute' ),
637             $five_days_ahead->truncate( to => 'minute' ),
638             'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
639         );
640     };
641
642     # Too many renewals
643
644     # set policy to forbid renewals
645     $dbh->do('UPDATE issuingrules SET norenewalbefore = NULL, renewalsallowed = 0');
646
647     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
648     is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
649     is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
650
651     # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
652     t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
653     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
654
655     C4::Overdues::UpdateFine(
656         {
657             issue_id       => $issue->id(),
658             itemnumber     => $itemnumber,
659             borrowernumber => $renewing_borrower->{borrowernumber},
660             amount         => 15.00,
661             type           => q{},
662             due            => Koha::DateUtils::output_pref($datedue)
663         }
664     );
665
666     LostItem( $itemnumber, 1 );
667
668     my $item = Koha::Database->new()->schema()->resultset('Item')->find($itemnumber);
669     ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
670
671     my $total_due = $dbh->selectrow_array(
672         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
673         undef, $renewing_borrower->{borrowernumber}
674     );
675
676     ok( $total_due == 12, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
677
678     C4::Context->dbh->do("DELETE FROM accountlines");
679
680     t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
681     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
682
683     C4::Overdues::UpdateFine(
684         {
685             issue_id       => $issue2->id(),
686             itemnumber     => $itemnumber2,
687             borrowernumber => $renewing_borrower->{borrowernumber},
688             amount         => 15.00,
689             type           => q{},
690             due            => Koha::DateUtils::output_pref($datedue)
691         }
692     );
693
694     LostItem( $itemnumber2, 0 );
695
696     my $item2 = Koha::Database->new()->schema()->resultset('Item')->find($itemnumber2);
697     ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
698
699     $total_due = $dbh->selectrow_array(
700         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
701         undef, $renewing_borrower->{borrowernumber}
702     );
703
704     ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
705
706     my $future = dt_from_string();
707     $future->add( days => 7 );
708     my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
709     ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
710
711     # Users cannot renew any item if there is an overdue item
712     t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
713     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber6);
714     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
715     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber7);
716     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
717
718   }
719
720 {
721     # GetUpcomingDueIssues tests
722     my $barcode  = 'R00000342';
723     my $barcode2 = 'R00000343';
724     my $barcode3 = 'R00000344';
725     my $branch   = $library2->{branchcode};
726
727     #Create another record
728     my $biblio2 = MARC::Record->new();
729     my $title2 = 'Something is worng here';
730     $biblio2->append_fields(
731         MARC::Field->new('100', ' ', ' ', a => 'Anonymous'),
732         MARC::Field->new('245', ' ', ' ', a => $title2),
733     );
734     my ($biblionumber2, $biblioitemnumber2) = AddBiblio($biblio2, '');
735
736     #Create third item
737     AddItem(
738         {
739             homebranch       => $branch,
740             holdingbranch    => $branch,
741             barcode          => $barcode3,
742             itype            => $itemtype
743         },
744         $biblionumber2
745     );
746
747     # Create a borrower
748     my %a_borrower_data = (
749         firstname =>  'Fridolyn',
750         surname => 'SOMERS',
751         categorycode => 'S',
752         branchcode => $branch,
753     );
754
755     my $a_borrower_borrowernumber = AddMember(%a_borrower_data);
756     my $a_borrower = GetMember( borrowernumber => $a_borrower_borrowernumber );
757
758     my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
759     my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
760     my $today = DateTime->today(time_zone => C4::Context->tz());
761
762     my $issue = AddIssue( $a_borrower, $barcode, $yesterday );
763     my $datedue = dt_from_string( $issue->date_due() );
764     my $issue2 = AddIssue( $a_borrower, $barcode2, $two_days_ahead );
765     my $datedue2 = dt_from_string( $issue->date_due() );
766
767     my $upcoming_dues;
768
769     # GetUpcomingDueIssues tests
770     for my $i(0..1) {
771         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
772         is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
773     }
774
775     #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
776     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
777     is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
778
779     for my $i(3..5) {
780         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
781         is ( scalar( @$upcoming_dues ), 1,
782             "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
783     }
784
785     # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
786
787     my $issue3 = AddIssue( $a_borrower, $barcode3, $today );
788
789     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
790     is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
791
792     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
793     is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
794
795     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
796     is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
797
798     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 }  );
799     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
800
801     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
802     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
803
804     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
805     is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
806
807 }
808
809 {
810     my $barcode  = '1234567890';
811     my $branch   = $library2->{branchcode};
812
813     my $biblio = MARC::Record->new();
814     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
815
816     #Create third item
817     my ( undef, undef, $itemnumber ) = AddItem(
818         {
819             homebranch       => $branch,
820             holdingbranch    => $branch,
821             barcode          => $barcode,
822             itype            => $itemtype
823         },
824         $biblionumber
825     );
826
827     # Create a borrower
828     my %a_borrower_data = (
829         firstname =>  'Kyle',
830         surname => 'Hall',
831         categorycode => 'S',
832         branchcode => $branch,
833     );
834
835     my $borrowernumber = AddMember(%a_borrower_data);
836
837     my $issue = AddIssue( GetMember( borrowernumber => $borrowernumber ), $barcode );
838     UpdateFine(
839         {
840             issue_id       => $issue->id(),
841             itemnumber     => $itemnumber,
842             borrowernumber => $borrowernumber,
843             amount         => 0
844         }
845     );
846
847     my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $itemnumber );
848     my $count = $hr->{count};
849
850     is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
851 }
852
853 {
854     $dbh->do('DELETE FROM issues');
855     $dbh->do('DELETE FROM items');
856     $dbh->do('DELETE FROM issuingrules');
857     $dbh->do(
858         q{
859         INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, maxissueqty, issuelength, lengthunit, renewalsallowed, renewalperiod,
860                     norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
861         },
862         {},
863         '*', '*', '*', 25,
864         20,  14,  'days',
865         1,   7,
866         undef,  0,
867         .10, 1
868     );
869     my $biblio = MARC::Record->new();
870     my ( $biblionumber, $biblioitemnumber ) = AddBiblio( $biblio, '' );
871
872     my $barcode1 = '1234';
873     my ( undef, undef, $itemnumber1 ) = AddItem(
874         {
875             homebranch    => $library2->{branchcode},
876             holdingbranch => $library2->{branchcode},
877             barcode       => $barcode1,
878             itype         => $itemtype
879         },
880         $biblionumber
881     );
882     my $barcode2 = '4321';
883     my ( undef, undef, $itemnumber2 ) = AddItem(
884         {
885             homebranch    => $library2->{branchcode},
886             holdingbranch => $library2->{branchcode},
887             barcode       => $barcode2,
888             itype         => $itemtype
889         },
890         $biblionumber
891     );
892
893     my $borrowernumber1 = AddMember(
894         firstname    => 'Kyle',
895         surname      => 'Hall',
896         categorycode => 'S',
897         branchcode   => $library2->{branchcode},
898     );
899     my $borrowernumber2 = AddMember(
900         firstname    => 'Chelsea',
901         surname      => 'Hall',
902         categorycode => 'S',
903         branchcode   => $library2->{branchcode},
904     );
905
906     my $borrower1 = GetMember( borrowernumber => $borrowernumber1 );
907     my $borrower2 = GetMember( borrowernumber => $borrowernumber2 );
908
909     my $issue = AddIssue( $borrower1, $barcode1 );
910
911     my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
912     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
913
914     AddReserve(
915         $library2->{branchcode}, $borrowernumber2, $biblionumber,
916         '',  1, undef, undef, '',
917         undef, undef, undef
918     );
919
920     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
921     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
922     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
923     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
924
925     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
926     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
927     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
928     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
929
930     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
931     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
932     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
933     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
934
935     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
936     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
937     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
938     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
939
940     # Setting item not checked out to be not for loan but holdable
941     ModItem({ notforloan => -1 }, $biblionumber, $itemnumber2);
942
943     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
944     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' );
945 }
946
947 {
948     # Don't allow renewing onsite checkout
949     my $barcode  = 'R00000XXX';
950     my $branch   = $library->{branchcode};
951
952     #Create another record
953     my $biblio = MARC::Record->new();
954     $biblio->append_fields(
955         MARC::Field->new('100', ' ', ' ', a => 'Anonymous'),
956         MARC::Field->new('245', ' ', ' ', a => 'A title'),
957     );
958     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
959
960     my (undef, undef, $itemnumber) = AddItem(
961         {
962             homebranch       => $branch,
963             holdingbranch    => $branch,
964             barcode          => $barcode,
965             itype            => $itemtype
966         },
967         $biblionumber
968     );
969
970     my $borrowernumber = AddMember(
971         firstname =>  'fn',
972         surname => 'dn',
973         categorycode => 'S',
974         branchcode => $branch,
975     );
976
977     my $borrower = GetMember( borrowernumber => $borrowernumber );
978     my $issue = AddIssue( $borrower, $barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
979     my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $itemnumber );
980     is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
981     is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
982 }
983
984 {
985     my $library = $builder->build({ source => 'Branch' });
986
987     my $biblio = MARC::Record->new();
988     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
989
990     my $barcode = 'just a barcode';
991     my ( undef, undef, $itemnumber ) = AddItem(
992         {
993             homebranch       => $library->{branchcode},
994             holdingbranch    => $library->{branchcode},
995             barcode          => $barcode,
996             itype            => $itemtype
997         },
998         $biblionumber,
999     );
1000
1001     my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode} } } );
1002
1003     my $issue = AddIssue( GetMember( borrowernumber => $patron->{borrowernumber} ), $barcode );
1004     UpdateFine(
1005         {
1006             issue_id       => $issue->id(),
1007             itemnumber     => $itemnumber,
1008             borrowernumber => $patron->{borrowernumber},
1009             amount         => 1,
1010         }
1011     );
1012     UpdateFine(
1013         {
1014             issue_id       => $issue->id(),
1015             itemnumber     => $itemnumber,
1016             borrowernumber => $patron->{borrowernumber},
1017             amount         => 2,
1018         }
1019     );
1020     is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1021 }
1022
1023 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1024     plan tests => 23;
1025
1026     my $homebranch    = $builder->build( { source => 'Branch' } );
1027     my $holdingbranch = $builder->build( { source => 'Branch' } );
1028     my $otherbranch   = $builder->build( { source => 'Branch' } );
1029     my $patron_1      = $builder->build( { source => 'Borrower' } );
1030     my $patron_2      = $builder->build( { source => 'Borrower' } );
1031
1032     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1033     my $item = $builder->build(
1034         {   source => 'Item',
1035             value  => {
1036                 homebranch    => $homebranch->{branchcode},
1037                 holdingbranch => $holdingbranch->{branchcode},
1038                 notforloan    => 0,
1039                 itemlost      => 0,
1040                 withdrawn     => 0,
1041                 biblionumber  => $biblioitem->{biblionumber}
1042             }
1043         }
1044     );
1045
1046     set_userenv($holdingbranch);
1047
1048     my $issue = AddIssue( $patron_1, $item->{barcode} );
1049     is( ref($issue), 'Koha::Schema::Result::Issue' );    # FIXME Should be Koha::Issue
1050
1051     my ( $error, $question, $alerts );
1052
1053     # AllowReturnToBranch == anywhere
1054     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1055     ## Can be issued from homebranch
1056     set_userenv($homebranch);
1057     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1058     is( keys(%$error) + keys(%$alerts),        0 );
1059     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
1060     ## Can be issued from holdingbranch
1061     set_userenv($holdingbranch);
1062     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1063     is( keys(%$error) + keys(%$alerts),        0 );
1064     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
1065     ## Can be issued from another branch
1066     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1067     is( keys(%$error) + keys(%$alerts),        0 );
1068     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
1069
1070     # AllowReturnToBranch == holdingbranch
1071     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1072     ## Cannot be issued from homebranch
1073     set_userenv($homebranch);
1074     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1075     is( keys(%$question) + keys(%$alerts),  0 );
1076     is( exists $error->{RETURN_IMPOSSIBLE}, 1 );
1077     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
1078     ## Can be issued from holdinbranch
1079     set_userenv($holdingbranch);
1080     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1081     is( keys(%$error) + keys(%$alerts),        0 );
1082     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
1083     ## Cannot be issued from another branch
1084     set_userenv($otherbranch);
1085     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1086     is( keys(%$question) + keys(%$alerts),  0 );
1087     is( exists $error->{RETURN_IMPOSSIBLE}, 1 );
1088     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
1089
1090     # AllowReturnToBranch == homebranch
1091     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1092     ## Can be issued from holdinbranch
1093     set_userenv($homebranch);
1094     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1095     is( keys(%$error) + keys(%$alerts),        0 );
1096     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
1097     ## Cannot be issued from holdinbranch
1098     set_userenv($holdingbranch);
1099     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1100     is( keys(%$question) + keys(%$alerts),  0 );
1101     is( exists $error->{RETURN_IMPOSSIBLE}, 1 );
1102     is( $error->{branch_to_return},         $homebranch->{branchcode} );
1103     ## Cannot be issued from holdinbranch
1104     set_userenv($otherbranch);
1105     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1106     is( keys(%$question) + keys(%$alerts),  0 );
1107     is( exists $error->{RETURN_IMPOSSIBLE}, 1 );
1108     is( $error->{branch_to_return},         $homebranch->{branchcode} );
1109
1110     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1111 };
1112
1113 subtest 'AddIssue & AllowReturnToBranch' => sub {
1114     plan tests => 9;
1115
1116     my $homebranch    = $builder->build( { source => 'Branch' } );
1117     my $holdingbranch = $builder->build( { source => 'Branch' } );
1118     my $otherbranch   = $builder->build( { source => 'Branch' } );
1119     my $patron_1      = $builder->build( { source => 'Borrower' } );
1120     my $patron_2      = $builder->build( { source => 'Borrower' } );
1121
1122     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1123     my $item = $builder->build(
1124         {   source => 'Item',
1125             value  => {
1126                 homebranch    => $homebranch->{branchcode},
1127                 holdingbranch => $holdingbranch->{branchcode},
1128                 notforloan    => 0,
1129                 itemlost      => 0,
1130                 withdrawn     => 0,
1131                 biblionumber  => $biblioitem->{biblionumber}
1132             }
1133         }
1134     );
1135
1136     set_userenv($holdingbranch);
1137
1138     my $ref_issue = 'Koha::Schema::Result::Issue'; # FIXME Should be Koha::Issue
1139     my $issue = AddIssue( $patron_1, $item->{barcode} );
1140
1141     my ( $error, $question, $alerts );
1142
1143     # AllowReturnToBranch == homebranch
1144     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1145     ## Can be issued from homebranch
1146     set_userenv($homebranch);
1147     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1148     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1149     ## Can be issued from holdinbranch
1150     set_userenv($holdingbranch);
1151     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1152     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1153     ## Can be issued from another branch
1154     set_userenv($otherbranch);
1155     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1156     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1157
1158     # AllowReturnToBranch == holdinbranch
1159     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1160     ## Cannot be issued from homebranch
1161     set_userenv($homebranch);
1162     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1163     ## Can be issued from holdingbranch
1164     set_userenv($holdingbranch);
1165     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1166     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1167     ## Cannot be issued from another branch
1168     set_userenv($otherbranch);
1169     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1170
1171     # AllowReturnToBranch == homebranch
1172     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1173     ## Can be issued from homebranch
1174     set_userenv($homebranch);
1175     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1176     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1177     ## Cannot be issued from holdinbranch
1178     set_userenv($holdingbranch);
1179     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1180     ## Cannot be issued from another branch
1181     set_userenv($otherbranch);
1182     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1183     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1184 };
1185
1186 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1187     plan tests => 8;
1188
1189     my $library = $builder->build( { source => 'Branch' } );
1190     my $patron  = $builder->build( { source => 'Borrower' } );
1191
1192     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1193     my $item_1 = $builder->build(
1194         {   source => 'Item',
1195             value  => {
1196                 homebranch    => $library->{branchcode},
1197                 holdingbranch => $library->{branchcode},
1198                 notforloan    => 0,
1199                 itemlost      => 0,
1200                 withdrawn     => 0,
1201                 biblionumber  => $biblioitem_1->{biblionumber}
1202             }
1203         }
1204     );
1205     my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1206     my $item_2 = $builder->build(
1207         {   source => 'Item',
1208             value  => {
1209                 homebranch    => $library->{branchcode},
1210                 holdingbranch => $library->{branchcode},
1211                 notforloan    => 0,
1212                 itemlost      => 0,
1213                 withdrawn     => 0,
1214                 biblionumber  => $biblioitem_2->{biblionumber}
1215             }
1216         }
1217     );
1218
1219     my ( $error, $question, $alerts );
1220
1221     # Patron cannot issue item_1, he has overdues
1222     my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1223     my $issue = AddIssue( $patron, $item_1->{barcode}, $yesterday );    # Add an overdue
1224
1225     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1226     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1227     is( keys(%$error) + keys(%$alerts),  0 );
1228     is( $question->{USERBLOCKEDOVERDUE}, 1 );
1229
1230     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1231     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1232     is( keys(%$question) + keys(%$alerts), 0 );
1233     is( $error->{USERBLOCKEDOVERDUE},      1 );
1234
1235     # Patron cannot issue item_1, he is debarred
1236     my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1237     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->{borrowernumber}, expiration => $tomorrow } );
1238     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1239     is( keys(%$question) + keys(%$alerts), 0 );
1240     is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ) );
1241
1242     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->{borrowernumber} } );
1243     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1244     is( keys(%$question) + keys(%$alerts), 0 );
1245     is( $error->{USERBLOCKEDNOENDDATE},    '9999-12-31' );
1246 };
1247
1248 sub set_userenv {
1249     my ( $library ) = @_;
1250     C4::Context->set_userenv(0,0,0,'firstname','surname', $library->{branchcode}, $library->{branchname}, '', '', '');
1251 }
1252
1253 1;