Bug 17278: Fix test compilation errors
[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             type           => q{}
845         }
846     );
847
848     my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $itemnumber );
849     my $count = $hr->{count};
850
851     is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
852 }
853
854 {
855     $dbh->do('DELETE FROM issues');
856     $dbh->do('DELETE FROM items');
857     $dbh->do('DELETE FROM issuingrules');
858     $dbh->do(
859         q{
860         INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, maxissueqty, issuelength, lengthunit, renewalsallowed, renewalperiod,
861                     norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
862         },
863         {},
864         '*', '*', '*', 25,
865         20,  14,  'days',
866         1,   7,
867         undef,  0,
868         .10, 1
869     );
870     my $biblio = MARC::Record->new();
871     my ( $biblionumber, $biblioitemnumber ) = AddBiblio( $biblio, '' );
872
873     my $barcode1 = '1234';
874     my ( undef, undef, $itemnumber1 ) = AddItem(
875         {
876             homebranch    => $library2->{branchcode},
877             holdingbranch => $library2->{branchcode},
878             barcode       => $barcode1,
879             itype         => $itemtype
880         },
881         $biblionumber
882     );
883     my $barcode2 = '4321';
884     my ( undef, undef, $itemnumber2 ) = AddItem(
885         {
886             homebranch    => $library2->{branchcode},
887             holdingbranch => $library2->{branchcode},
888             barcode       => $barcode2,
889             itype         => $itemtype
890         },
891         $biblionumber
892     );
893
894     my $borrowernumber1 = AddMember(
895         firstname    => 'Kyle',
896         surname      => 'Hall',
897         categorycode => 'S',
898         branchcode   => $library2->{branchcode},
899     );
900     my $borrowernumber2 = AddMember(
901         firstname    => 'Chelsea',
902         surname      => 'Hall',
903         categorycode => 'S',
904         branchcode   => $library2->{branchcode},
905     );
906
907     my $borrower1 = GetMember( borrowernumber => $borrowernumber1 );
908     my $borrower2 = GetMember( borrowernumber => $borrowernumber2 );
909
910     my $issue = AddIssue( $borrower1, $barcode1 );
911
912     my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
913     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
914
915     AddReserve(
916         $library2->{branchcode}, $borrowernumber2, $biblionumber,
917         '',  1, undef, undef, '',
918         undef, undef, undef
919     );
920
921     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
922     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
923     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
924     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
925
926     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
927     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
928     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
929     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
930
931     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
932     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
933     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
934     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
935
936     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
937     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
938     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
939     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
940
941     # Setting item not checked out to be not for loan but holdable
942     ModItem({ notforloan => -1 }, $biblionumber, $itemnumber2);
943
944     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
945     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' );
946 }
947
948 {
949     # Don't allow renewing onsite checkout
950     my $barcode  = 'R00000XXX';
951     my $branch   = $library->{branchcode};
952
953     #Create another record
954     my $biblio = MARC::Record->new();
955     $biblio->append_fields(
956         MARC::Field->new('100', ' ', ' ', a => 'Anonymous'),
957         MARC::Field->new('245', ' ', ' ', a => 'A title'),
958     );
959     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
960
961     my (undef, undef, $itemnumber) = AddItem(
962         {
963             homebranch       => $branch,
964             holdingbranch    => $branch,
965             barcode          => $barcode,
966             itype            => $itemtype
967         },
968         $biblionumber
969     );
970
971     my $borrowernumber = AddMember(
972         firstname =>  'fn',
973         surname => 'dn',
974         categorycode => 'S',
975         branchcode => $branch,
976     );
977
978     my $borrower = GetMember( borrowernumber => $borrowernumber );
979     my $issue = AddIssue( $borrower, $barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
980     my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $itemnumber );
981     is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
982     is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
983 }
984
985 {
986     my $library = $builder->build({ source => 'Branch' });
987
988     my $biblio = MARC::Record->new();
989     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
990
991     my $barcode = 'just a barcode';
992     my ( undef, undef, $itemnumber ) = AddItem(
993         {
994             homebranch       => $library->{branchcode},
995             holdingbranch    => $library->{branchcode},
996             barcode          => $barcode,
997             itype            => $itemtype
998         },
999         $biblionumber,
1000     );
1001
1002     my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode} } } );
1003
1004     my $issue = AddIssue( GetMember( borrowernumber => $patron->{borrowernumber} ), $barcode );
1005     UpdateFine(
1006         {
1007             issue_id       => $issue->id(),
1008             itemnumber     => $itemnumber,
1009             borrowernumber => $patron->{borrowernumber},
1010             amount         => 1,
1011             type           => q{}
1012         }
1013     );
1014     UpdateFine(
1015         {
1016             issue_id       => $issue->id(),
1017             itemnumber     => $itemnumber,
1018             borrowernumber => $patron->{borrowernumber},
1019             amount         => 2,
1020             type           => q{}
1021         }
1022     );
1023     is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1024 }
1025
1026 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1027     plan tests => 23;
1028
1029     my $homebranch    = $builder->build( { source => 'Branch' } );
1030     my $holdingbranch = $builder->build( { source => 'Branch' } );
1031     my $otherbranch   = $builder->build( { source => 'Branch' } );
1032     my $patron_1      = $builder->build( { source => 'Borrower' } );
1033     my $patron_2      = $builder->build( { source => 'Borrower' } );
1034
1035     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1036     my $item = $builder->build(
1037         {   source => 'Item',
1038             value  => {
1039                 homebranch    => $homebranch->{branchcode},
1040                 holdingbranch => $holdingbranch->{branchcode},
1041                 notforloan    => 0,
1042                 itemlost      => 0,
1043                 withdrawn     => 0,
1044                 biblionumber  => $biblioitem->{biblionumber}
1045             }
1046         }
1047     );
1048
1049     set_userenv($holdingbranch);
1050
1051     my $issue = AddIssue( $patron_1, $item->{barcode} );
1052     is( ref($issue), 'Koha::Schema::Result::Issue' );    # FIXME Should be Koha::Issue
1053
1054     my ( $error, $question, $alerts );
1055
1056     # AllowReturnToBranch == anywhere
1057     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1058     ## Can be issued from homebranch
1059     set_userenv($homebranch);
1060     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1061     is( keys(%$error) + keys(%$alerts),        0 );
1062     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
1063     ## Can be issued from holdingbranch
1064     set_userenv($holdingbranch);
1065     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1066     is( keys(%$error) + keys(%$alerts),        0 );
1067     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
1068     ## Can be issued from another branch
1069     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1070     is( keys(%$error) + keys(%$alerts),        0 );
1071     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
1072
1073     # AllowReturnToBranch == holdingbranch
1074     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1075     ## Cannot be issued from homebranch
1076     set_userenv($homebranch);
1077     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1078     is( keys(%$question) + keys(%$alerts),  0 );
1079     is( exists $error->{RETURN_IMPOSSIBLE}, 1 );
1080     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
1081     ## Can be issued from holdinbranch
1082     set_userenv($holdingbranch);
1083     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1084     is( keys(%$error) + keys(%$alerts),        0 );
1085     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
1086     ## Cannot be issued from another branch
1087     set_userenv($otherbranch);
1088     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1089     is( keys(%$question) + keys(%$alerts),  0 );
1090     is( exists $error->{RETURN_IMPOSSIBLE}, 1 );
1091     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
1092
1093     # AllowReturnToBranch == homebranch
1094     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1095     ## Can be issued from holdinbranch
1096     set_userenv($homebranch);
1097     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1098     is( keys(%$error) + keys(%$alerts),        0 );
1099     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
1100     ## Cannot be issued from holdinbranch
1101     set_userenv($holdingbranch);
1102     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1103     is( keys(%$question) + keys(%$alerts),  0 );
1104     is( exists $error->{RETURN_IMPOSSIBLE}, 1 );
1105     is( $error->{branch_to_return},         $homebranch->{branchcode} );
1106     ## Cannot be issued from holdinbranch
1107     set_userenv($otherbranch);
1108     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1109     is( keys(%$question) + keys(%$alerts),  0 );
1110     is( exists $error->{RETURN_IMPOSSIBLE}, 1 );
1111     is( $error->{branch_to_return},         $homebranch->{branchcode} );
1112
1113     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1114 };
1115
1116 subtest 'AddIssue & AllowReturnToBranch' => sub {
1117     plan tests => 9;
1118
1119     my $homebranch    = $builder->build( { source => 'Branch' } );
1120     my $holdingbranch = $builder->build( { source => 'Branch' } );
1121     my $otherbranch   = $builder->build( { source => 'Branch' } );
1122     my $patron_1      = $builder->build( { source => 'Borrower' } );
1123     my $patron_2      = $builder->build( { source => 'Borrower' } );
1124
1125     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1126     my $item = $builder->build(
1127         {   source => 'Item',
1128             value  => {
1129                 homebranch    => $homebranch->{branchcode},
1130                 holdingbranch => $holdingbranch->{branchcode},
1131                 notforloan    => 0,
1132                 itemlost      => 0,
1133                 withdrawn     => 0,
1134                 biblionumber  => $biblioitem->{biblionumber}
1135             }
1136         }
1137     );
1138
1139     set_userenv($holdingbranch);
1140
1141     my $ref_issue = 'Koha::Schema::Result::Issue'; # FIXME Should be Koha::Issue
1142     my $issue = AddIssue( $patron_1, $item->{barcode} );
1143
1144     my ( $error, $question, $alerts );
1145
1146     # AllowReturnToBranch == homebranch
1147     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1148     ## Can be issued from homebranch
1149     set_userenv($homebranch);
1150     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1151     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1152     ## Can be issued from holdinbranch
1153     set_userenv($holdingbranch);
1154     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1155     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1156     ## Can be issued from another branch
1157     set_userenv($otherbranch);
1158     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1159     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1160
1161     # AllowReturnToBranch == holdinbranch
1162     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1163     ## Cannot be issued from homebranch
1164     set_userenv($homebranch);
1165     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1166     ## Can be issued from holdingbranch
1167     set_userenv($holdingbranch);
1168     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1169     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1170     ## Cannot be issued from another branch
1171     set_userenv($otherbranch);
1172     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1173
1174     # AllowReturnToBranch == homebranch
1175     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1176     ## Can be issued from homebranch
1177     set_userenv($homebranch);
1178     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1179     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1180     ## Cannot be issued from holdinbranch
1181     set_userenv($holdingbranch);
1182     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1183     ## Cannot be issued from another branch
1184     set_userenv($otherbranch);
1185     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1186     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1187 };
1188
1189 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1190     plan tests => 8;
1191
1192     my $library = $builder->build( { source => 'Branch' } );
1193     my $patron  = $builder->build( { source => 'Borrower' } );
1194
1195     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1196     my $item_1 = $builder->build(
1197         {   source => 'Item',
1198             value  => {
1199                 homebranch    => $library->{branchcode},
1200                 holdingbranch => $library->{branchcode},
1201                 notforloan    => 0,
1202                 itemlost      => 0,
1203                 withdrawn     => 0,
1204                 biblionumber  => $biblioitem_1->{biblionumber}
1205             }
1206         }
1207     );
1208     my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1209     my $item_2 = $builder->build(
1210         {   source => 'Item',
1211             value  => {
1212                 homebranch    => $library->{branchcode},
1213                 holdingbranch => $library->{branchcode},
1214                 notforloan    => 0,
1215                 itemlost      => 0,
1216                 withdrawn     => 0,
1217                 biblionumber  => $biblioitem_2->{biblionumber}
1218             }
1219         }
1220     );
1221
1222     my ( $error, $question, $alerts );
1223
1224     # Patron cannot issue item_1, he has overdues
1225     my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1226     my $issue = AddIssue( $patron, $item_1->{barcode}, $yesterday );    # Add an overdue
1227
1228     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1229     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1230     is( keys(%$error) + keys(%$alerts),  0 );
1231     is( $question->{USERBLOCKEDOVERDUE}, 1 );
1232
1233     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1234     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1235     is( keys(%$question) + keys(%$alerts), 0 );
1236     is( $error->{USERBLOCKEDOVERDUE},      1 );
1237
1238     # Patron cannot issue item_1, he is debarred
1239     my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1240     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->{borrowernumber}, expiration => $tomorrow } );
1241     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1242     is( keys(%$question) + keys(%$alerts), 0 );
1243     is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ) );
1244
1245     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->{borrowernumber} } );
1246     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1247     is( keys(%$question) + keys(%$alerts), 0 );
1248     is( $error->{USERBLOCKEDNOENDDATE},    '9999-12-31' );
1249 };
1250
1251 sub set_userenv {
1252     my ( $library ) = @_;
1253     C4::Context->set_userenv(0,0,0,'firstname','surname', $library->{branchcode}, $library->{branchname}, '', '', '');
1254 }
1255
1256 1;