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