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