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