f1f7a5903dc59293f60198170f54f4e4c0c542f3
[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 => 121;
21
22 use Data::Dumper;
23 use DateTime;
24 use POSIX qw( floor );
25 use t::lib::Mocks;
26 use t::lib::TestBuilder;
27
28 use C4::Calendar;
29 use C4::Circulation;
30 use C4::Biblio;
31 use C4::Items;
32 use C4::Log;
33 use C4::Reserves;
34 use C4::Overdues qw(UpdateFine CalcFine);
35 use Koha::DateUtils;
36 use Koha::Database;
37 use Koha::IssuingRules;
38 use Koha::Checkouts;
39 use Koha::Patrons;
40 use Koha::Subscriptions;
41 use Koha::Account::Lines;
42 use Koha::Account::Offsets;
43
44 my $schema = Koha::Database->schema;
45 $schema->storage->txn_begin;
46 my $builder = t::lib::TestBuilder->new;
47 my $dbh = C4::Context->dbh;
48
49 # Start transaction
50 $dbh->{RaiseError} = 1;
51
52 my $cache = Koha::Caches->get_instance();
53 $dbh->do(q|DELETE FROM special_holidays|);
54 $dbh->do(q|DELETE FROM repeatable_holidays|);
55 $cache->clear_from_cache('single_holidays');
56
57 # Start with a clean slate
58 $dbh->do('DELETE FROM issues');
59 $dbh->do('DELETE FROM borrowers');
60
61 my $library = $builder->build({
62     source => 'Branch',
63 });
64 my $library2 = $builder->build({
65     source => 'Branch',
66 });
67 my $itemtype = $builder->build(
68     {   source => 'Itemtype',
69         value  => { notforloan => undef, rentalcharge => 0, defaultreplacecost => undef, processfee => undef }
70     }
71 )->{itemtype};
72 my $patron_category = $builder->build(
73     {
74         source => 'Category',
75         value  => {
76             category_type                 => 'P',
77             enrolmentfee                  => 0,
78             BlockExpiredPatronOpacActions => -1, # Pick the pref value
79         }
80     }
81 );
82
83 my $CircControl = C4::Context->preference('CircControl');
84 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
85
86 my $item = {
87     homebranch => $library2->{branchcode},
88     holdingbranch => $library2->{branchcode}
89 };
90
91 my $borrower = {
92     branchcode => $library2->{branchcode}
93 };
94
95 # No userenv, PickupLibrary
96 t::lib::Mocks::mock_preference('IndependentBranches', '0');
97 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
98 is(
99     C4::Context->preference('CircControl'),
100     'PickupLibrary',
101     'CircControl changed to PickupLibrary'
102 );
103 is(
104     C4::Circulation::_GetCircControlBranch($item, $borrower),
105     $item->{$HomeOrHoldingBranch},
106     '_GetCircControlBranch returned item branch (no userenv defined)'
107 );
108
109 # No userenv, PatronLibrary
110 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
111 is(
112     C4::Context->preference('CircControl'),
113     'PatronLibrary',
114     'CircControl changed to PatronLibrary'
115 );
116 is(
117     C4::Circulation::_GetCircControlBranch($item, $borrower),
118     $borrower->{branchcode},
119     '_GetCircControlBranch returned borrower branch'
120 );
121
122 # No userenv, ItemHomeLibrary
123 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
124 is(
125     C4::Context->preference('CircControl'),
126     'ItemHomeLibrary',
127     'CircControl changed to ItemHomeLibrary'
128 );
129 is(
130     $item->{$HomeOrHoldingBranch},
131     C4::Circulation::_GetCircControlBranch($item, $borrower),
132     '_GetCircControlBranch returned item branch'
133 );
134
135 # Now, set a userenv
136 C4::Context->_new_userenv('xxx');
137 C4::Context->set_userenv(0,0,0,'firstname','surname', $library2->{branchcode}, 'Midway Public Library', '', '', '');
138 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
139
140 # Userenv set, PickupLibrary
141 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
142 is(
143     C4::Context->preference('CircControl'),
144     'PickupLibrary',
145     'CircControl changed to PickupLibrary'
146 );
147 is(
148     C4::Circulation::_GetCircControlBranch($item, $borrower),
149     $library2->{branchcode},
150     '_GetCircControlBranch returned current branch'
151 );
152
153 # Userenv set, PatronLibrary
154 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
155 is(
156     C4::Context->preference('CircControl'),
157     'PatronLibrary',
158     'CircControl changed to PatronLibrary'
159 );
160 is(
161     C4::Circulation::_GetCircControlBranch($item, $borrower),
162     $borrower->{branchcode},
163     '_GetCircControlBranch returned borrower branch'
164 );
165
166 # Userenv set, ItemHomeLibrary
167 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
168 is(
169     C4::Context->preference('CircControl'),
170     'ItemHomeLibrary',
171     'CircControl changed to ItemHomeLibrary'
172 );
173 is(
174     C4::Circulation::_GetCircControlBranch($item, $borrower),
175     $item->{$HomeOrHoldingBranch},
176     '_GetCircControlBranch returned item branch'
177 );
178
179 # Reset initial configuration
180 t::lib::Mocks::mock_preference('CircControl', $CircControl);
181 is(
182     C4::Context->preference('CircControl'),
183     $CircControl,
184     'CircControl reset to its initial value'
185 );
186
187 # Set a simple circ policy
188 $dbh->do('DELETE FROM issuingrules');
189 $dbh->do(
190     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
191                                 maxissueqty, issuelength, lengthunit,
192                                 renewalsallowed, renewalperiod,
193                                 norenewalbefore, auto_renew,
194                                 fine, chargeperiod)
195       VALUES (?, ?, ?, ?,
196               ?, ?, ?,
197               ?, ?,
198               ?, ?,
199               ?, ?
200              )
201     },
202     {},
203     '*', '*', '*', 25,
204     20, 14, 'days',
205     1, 7,
206     undef, 0,
207     .10, 1
208 );
209
210 # Test C4::Circulation::ProcessOfflinePayment
211 my $sth = C4::Context->dbh->prepare("SELECT COUNT(*) FROM accountlines WHERE amount = '-123.45' AND accounttype = 'Pay'");
212 $sth->execute();
213 my ( $original_count ) = $sth->fetchrow_array();
214
215 C4::Context->dbh->do("INSERT INTO borrowers ( cardnumber, surname, firstname, categorycode, branchcode ) VALUES ( '99999999999', 'Hall', 'Kyle', ?, ? )", undef, $patron_category->{categorycode}, $library2->{branchcode} );
216
217 C4::Circulation::ProcessOfflinePayment({ cardnumber => '99999999999', amount => '123.45' });
218
219 $sth->execute();
220 my ( $new_count ) = $sth->fetchrow_array();
221
222 ok( $new_count == $original_count  + 1, 'ProcessOfflinePayment makes payment correctly' );
223
224 C4::Context->dbh->do("DELETE FROM accountlines WHERE borrowernumber IN ( SELECT borrowernumber FROM borrowers WHERE cardnumber = '99999999999' )");
225 C4::Context->dbh->do("DELETE FROM borrowers WHERE cardnumber = '99999999999'");
226 C4::Context->dbh->do("DELETE FROM accountlines");
227 {
228 # CanBookBeRenewed tests
229     C4::Context->set_preference('ItemsDeniedRenewal','');
230     # Generate test biblio
231     my $title = 'Silence in the library';
232     my ($biblionumber, $biblioitemnumber) = add_biblio($title, 'Moffat, Steven');
233
234     my $barcode = 'R00000342';
235     my $branch = $library2->{branchcode};
236
237     my ( $item_bibnum, $item_bibitemnum, $itemnumber ) = AddItem(
238         {
239             homebranch       => $branch,
240             holdingbranch    => $branch,
241             barcode          => $barcode,
242             replacementprice => 12.00,
243             itype            => $itemtype
244         },
245         $biblionumber
246     );
247
248     my $barcode2 = 'R00000343';
249     my ( $item_bibnum2, $item_bibitemnum2, $itemnumber2 ) = AddItem(
250         {
251             homebranch       => $branch,
252             holdingbranch    => $branch,
253             barcode          => $barcode2,
254             replacementprice => 23.00,
255             itype            => $itemtype
256         },
257         $biblionumber
258     );
259
260     my $barcode3 = 'R00000346';
261     my ( $item_bibnum3, $item_bibitemnum3, $itemnumber3 ) = AddItem(
262         {
263             homebranch       => $branch,
264             holdingbranch    => $branch,
265             barcode          => $barcode3,
266             replacementprice => 23.00,
267             itype            => $itemtype
268         },
269         $biblionumber
270     );
271
272     # Create borrowers
273     my %renewing_borrower_data = (
274         firstname =>  'John',
275         surname => 'Renewal',
276         categorycode => $patron_category->{categorycode},
277         branchcode => $branch,
278     );
279
280     my %reserving_borrower_data = (
281         firstname =>  'Katrin',
282         surname => 'Reservation',
283         categorycode => $patron_category->{categorycode},
284         branchcode => $branch,
285     );
286
287     my %hold_waiting_borrower_data = (
288         firstname =>  'Kyle',
289         surname => 'Reservation',
290         categorycode => $patron_category->{categorycode},
291         branchcode => $branch,
292     );
293
294     my %restricted_borrower_data = (
295         firstname =>  'Alice',
296         surname => 'Reservation',
297         categorycode => $patron_category->{categorycode},
298         debarred => '3228-01-01',
299         branchcode => $branch,
300     );
301
302     my %expired_borrower_data = (
303         firstname =>  'Ça',
304         surname => 'Glisse',
305         categorycode => $patron_category->{categorycode},
306         branchcode => $branch,
307         dateexpiry => dt_from_string->subtract( months => 1 ),
308     );
309
310     my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
311     my $reserving_borrowernumber = Koha::Patron->new(\%reserving_borrower_data)->store->borrowernumber;
312     my $hold_waiting_borrowernumber = Koha::Patron->new(\%hold_waiting_borrower_data)->store->borrowernumber;
313     my $restricted_borrowernumber = Koha::Patron->new(\%restricted_borrower_data)->store->borrowernumber;
314     my $expired_borrowernumber = Koha::Patron->new(\%expired_borrower_data)->store->borrowernumber;
315
316     my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
317     my $restricted_borrower = Koha::Patrons->find( $restricted_borrowernumber )->unblessed;
318     my $expired_borrower = Koha::Patrons->find( $expired_borrowernumber )->unblessed;
319
320     my $bibitems       = '';
321     my $priority       = '1';
322     my $resdate        = undef;
323     my $expdate        = undef;
324     my $notes          = '';
325     my $checkitem      = undef;
326     my $found          = undef;
327
328     my $issue = AddIssue( $renewing_borrower, $barcode);
329     my $datedue = dt_from_string( $issue->date_due() );
330     is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
331
332     my $issue2 = AddIssue( $renewing_borrower, $barcode2);
333     $datedue = dt_from_string( $issue->date_due() );
334     is (defined $issue2, 1, "Item 2 checked out, due date: " . $issue2->date_due());
335
336
337     my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $itemnumber } )->borrowernumber;
338     is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
339
340     my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber, 1);
341     is( $renewokay, 1, 'Can renew, no holds for this title or item');
342
343
344     # Biblio-level hold, renewal test
345     AddReserve(
346         $branch, $reserving_borrowernumber, $biblionumber,
347         $bibitems,  $priority, $resdate, $expdate, $notes,
348         $title, $checkitem, $found
349     );
350
351     # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
352     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
353     t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
354     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
355     is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
356     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
357     is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
358
359     # Now let's add an item level hold, we should no longer be able to renew the item
360     my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
361         {
362             borrowernumber => $hold_waiting_borrowernumber,
363             biblionumber   => $biblionumber,
364             itemnumber     => $itemnumber,
365             branchcode     => $branch,
366             priority       => 3,
367         }
368     );
369     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
370     is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
371     $hold->delete();
372
373     # 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
374     # be able to renew these items
375     $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
376         {
377             borrowernumber => $hold_waiting_borrowernumber,
378             biblionumber   => $biblionumber,
379             itemnumber     => $itemnumber3,
380             branchcode     => $branch,
381             priority       => 0,
382             found          => 'W'
383         }
384     );
385     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
386     is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
387     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
388     is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
389     t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
390
391     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
392     is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
393     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
394
395     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
396     is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
397     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
398
399     my $reserveid = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
400     my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber )->unblessed;
401     AddIssue($reserving_borrower, $barcode3);
402     my $reserve = $dbh->selectrow_hashref(
403         'SELECT * FROM old_reserves WHERE reserve_id = ?',
404         { Slice => {} },
405         $reserveid
406     );
407     is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
408
409     # Item-level hold, renewal test
410     AddReserve(
411         $branch, $reserving_borrowernumber, $biblionumber,
412         $bibitems,  $priority, $resdate, $expdate, $notes,
413         $title, $itemnumber, $found
414     );
415
416     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber, 1);
417     is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
418     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
419
420     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2, 1);
421     is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
422
423     # Items can't fill hold for reasons
424     ModItem({ notforloan => 1 }, $biblionumber, $itemnumber);
425     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber, 1);
426     is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
427     ModItem({ notforloan => 0, itype => $itemtype }, $biblionumber, $itemnumber);
428
429     # FIXME: Add more for itemtype not for loan etc.
430
431     # Restricted users cannot renew when RestrictionBlockRenewing is enabled
432     my $barcode5 = 'R00000347';
433     my ( $item_bibnum5, $item_bibitemnum5, $itemnumber5 ) = AddItem(
434         {
435             homebranch       => $branch,
436             holdingbranch    => $branch,
437             barcode          => $barcode5,
438             replacementprice => 23.00,
439             itype            => $itemtype
440         },
441         $biblionumber
442     );
443     my $datedue5 = AddIssue($restricted_borrower, $barcode5);
444     is (defined $datedue5, 1, "Item with date due checked out, due date: $datedue5");
445
446     t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
447     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
448     is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
449     ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrowernumber, $itemnumber5);
450     is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
451
452     # Users cannot renew an overdue item
453     my $barcode6 = 'R00000348';
454     my ( $item_bibnum6, $item_bibitemnum6, $itemnumber6 ) = AddItem(
455         {
456             homebranch       => $branch,
457             holdingbranch    => $branch,
458             barcode          => $barcode6,
459             replacementprice => 23.00,
460             itype            => $itemtype
461         },
462         $biblionumber
463     );
464
465     my $barcode7 = 'R00000349';
466     my ( $item_bibnum7, $item_bibitemnum7, $itemnumber7 ) = AddItem(
467         {
468             homebranch       => $branch,
469             holdingbranch    => $branch,
470             barcode          => $barcode7,
471             replacementprice => 23.00,
472             itype            => $itemtype
473         },
474         $biblionumber
475     );
476     my $datedue6 = AddIssue( $renewing_borrower, $barcode6);
477     is (defined $datedue6, 1, "Item 2 checked out, due date: ".$datedue6->date_due);
478
479     my $now = dt_from_string();
480     my $five_weeks = DateTime::Duration->new(weeks => 5);
481     my $five_weeks_ago = $now - $five_weeks;
482     t::lib::Mocks::mock_preference('finesMode', 'production');
483
484     my $passeddatedue1 = AddIssue($renewing_borrower, $barcode7, $five_weeks_ago);
485     is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: " . $passeddatedue1->date_due);
486
487     my ( $fine ) = CalcFine( GetItem(undef, $barcode7), $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
488     C4::Overdues::UpdateFine(
489         {
490             issue_id       => $passeddatedue1->id(),
491             itemnumber     => $itemnumber7,
492             borrowernumber => $renewing_borrower->{borrowernumber},
493             amount         => $fine,
494             type           => 'FU',
495             due            => Koha::DateUtils::output_pref($five_weeks_ago)
496         }
497     );
498
499     t::lib::Mocks::mock_preference('RenewalLog', 0);
500     my $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
501     my $old_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
502     AddRenewal( $renewing_borrower->{borrowernumber}, $itemnumber7, $branch );
503     my $new_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
504     is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
505
506     t::lib::Mocks::mock_preference('RenewalLog', 1);
507     $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
508     $old_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
509     AddRenewal( $renewing_borrower->{borrowernumber}, $itemnumber7, $branch );
510     $new_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
511     is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
512
513     my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $itemnumber7 } );
514     is( $fines->count, 2 );
515     is( $fines->next->accounttype, 'F', 'Fine on renewed item is closed out properly' );
516     is( $fines->next->accounttype, 'F', 'Fine on renewed item is closed out properly' );
517     $fines->delete();
518
519
520     my $old_issue_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["ISSUE"]) } );
521     my $old_renew_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
522     AddIssue( $renewing_borrower,$barcode7,Koha::DateUtils::output_pref({str=>$datedue6->date_due, dateformat =>'iso'}),0,$date, 0, undef );
523     $new_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
524     is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
525     $new_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["ISSUE"]) } );
526     is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
527
528     $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $itemnumber7 } );
529     $fines->delete();
530
531     t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
532     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber6);
533     is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
534     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber7);
535     is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
536
537
538     $hold = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $reserving_borrowernumber })->next;
539     $hold->cancel;
540
541     # Bug 14101
542     # Test automatic renewal before value for "norenewalbefore" in policy is set
543     # In this case automatic renewal is not permitted prior to due date
544     my $barcode4 = '11235813';
545     my ( $item_bibnum4, $item_bibitemnum4, $itemnumber4 ) = AddItem(
546         {
547             homebranch       => $branch,
548             holdingbranch    => $branch,
549             barcode          => $barcode4,
550             replacementprice => 16.00,
551             itype            => $itemtype
552         },
553         $biblionumber
554     );
555
556     $issue = AddIssue( $renewing_borrower, $barcode4, undef, undef, undef, undef, { auto_renew => 1 } );
557     ( $renewokay, $error ) =
558       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
559     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
560     is( $error, 'auto_too_soon',
561         'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
562
563     # Bug 7413
564     # Test premature manual renewal
565     $dbh->do('UPDATE issuingrules SET norenewalbefore = 7');
566
567     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
568     is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
569     is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
570
571     # Bug 14395
572     # Test 'exact time' setting for syspref NoRenewalBeforePrecision
573     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
574     is(
575         GetSoonestRenewDate( $renewing_borrowernumber, $itemnumber ),
576         $datedue->clone->add( days => -7 ),
577         'Bug 14395: Renewals permitted 7 days before due date, as expected'
578     );
579
580     # Bug 14395
581     # Test 'date' setting for syspref NoRenewalBeforePrecision
582     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
583     is(
584         GetSoonestRenewDate( $renewing_borrowernumber, $itemnumber ),
585         $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
586         'Bug 14395: Renewals permitted 7 days before due date, as expected'
587     );
588
589     # Bug 14101
590     # Test premature automatic renewal
591     ( $renewokay, $error ) =
592       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
593     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
594     is( $error, 'auto_too_soon',
595         'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
596     );
597
598     # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
599     # and test automatic renewal again
600     $dbh->do('UPDATE issuingrules SET norenewalbefore = 0');
601     ( $renewokay, $error ) =
602       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
603     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
604     is( $error, 'auto_too_soon',
605         'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
606     );
607
608     # Change policy so that loans can be renewed 99 days prior to the due date
609     # and test automatic renewal again
610     $dbh->do('UPDATE issuingrules SET norenewalbefore = 99');
611     ( $renewokay, $error ) =
612       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
613     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
614     is( $error, 'auto_renew',
615         'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
616     );
617
618     subtest "too_late_renewal / no_auto_renewal_after" => sub {
619         plan tests => 14;
620         my $item_to_auto_renew = $builder->build(
621             {   source => 'Item',
622                 value  => {
623                     biblionumber  => $biblionumber,
624                     homebranch    => $branch,
625                     holdingbranch => $branch,
626                 }
627             }
628         );
629
630         my $ten_days_before = dt_from_string->add( days => -10 );
631         my $ten_days_ahead  = dt_from_string->add( days => 10 );
632         AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
633
634         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 9');
635         ( $renewokay, $error ) =
636           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
637         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
638         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
639
640         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 10');
641         ( $renewokay, $error ) =
642           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
643         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
644         is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
645
646         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 11');
647         ( $renewokay, $error ) =
648           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
649         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
650         is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
651
652         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
653         ( $renewokay, $error ) =
654           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
655         is( $renewokay, 0,            'Do not renew, renewal is automatic' );
656         is( $error,     'auto_renew', 'Cannot renew, renew is automatic' );
657
658         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = NULL, no_auto_renewal_after_hard_limit = ?', undef, dt_from_string->add( days => -1 ) );
659         ( $renewokay, $error ) =
660           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
661         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
662         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
663
664         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 15, no_auto_renewal_after_hard_limit = ?', undef, dt_from_string->add( days => -1 ) );
665         ( $renewokay, $error ) =
666           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
667         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
668         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
669
670         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = NULL, no_auto_renewal_after_hard_limit = ?', undef, dt_from_string->add( days => 1 ) );
671         ( $renewokay, $error ) =
672           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
673         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
674         is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
675     };
676
677     subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew" => sub {
678         plan tests => 6;
679         my $item_to_auto_renew = $builder->build({
680             source => 'Item',
681             value => {
682                 biblionumber => $biblionumber,
683                 homebranch       => $branch,
684                 holdingbranch    => $branch,
685             }
686         });
687
688         my $ten_days_before = dt_from_string->add( days => -10 );
689         my $ten_days_ahead = dt_from_string->add( days => 10 );
690         AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
691
692         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
693         C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
694         C4::Context->set_preference('OPACFineNoRenewals','10');
695         my $fines_amount = 5;
696         C4::Accounts::manualinvoice( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber}, "Some fines", 'F', $fines_amount );
697         ( $renewokay, $error ) =
698           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
699         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
700         is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
701
702         C4::Accounts::manualinvoice( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber}, "Some fines", 'F', $fines_amount );
703         ( $renewokay, $error ) =
704           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
705         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
706         is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
707
708         C4::Accounts::manualinvoice( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber}, "Some fines", 'F', $fines_amount );
709         ( $renewokay, $error ) =
710           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
711         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
712         is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
713
714         $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
715     };
716
717     subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
718         plan tests => 6;
719         my $item_to_auto_renew = $builder->build({
720             source => 'Item',
721             value => {
722                 biblionumber => $biblionumber,
723                 homebranch       => $branch,
724                 holdingbranch    => $branch,
725             }
726         });
727
728         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
729
730         my $ten_days_before = dt_from_string->add( days => -10 );
731         my $ten_days_ahead = dt_from_string->add( days => 10 );
732
733         # Patron is expired and BlockExpiredPatronOpacActions=0
734         # => auto renew is allowed
735         t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
736         my $patron = $expired_borrower;
737         my $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
738         ( $renewokay, $error ) =
739           CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
740         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
741         is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
742         Koha::Checkouts->find( $checkout->issue_id )->delete;
743
744
745         # Patron is expired and BlockExpiredPatronOpacActions=1
746         # => auto renew is not allowed
747         t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
748         $patron = $expired_borrower;
749         $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
750         ( $renewokay, $error ) =
751           CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
752         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
753         is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
754         Koha::Checkouts->find( $checkout->issue_id )->delete;
755
756
757         # Patron is not expired and BlockExpiredPatronOpacActions=1
758         # => auto renew is allowed
759         t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
760         $patron = $renewing_borrower;
761         $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
762         ( $renewokay, $error ) =
763           CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
764         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
765         is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
766         Koha::Checkouts->find( $checkout->issue_id )->delete;
767     };
768
769     subtest "GetLatestAutoRenewDate" => sub {
770         plan tests => 5;
771         my $item_to_auto_renew = $builder->build(
772             {   source => 'Item',
773                 value  => {
774                     biblionumber  => $biblionumber,
775                     homebranch    => $branch,
776                     holdingbranch => $branch,
777                 }
778             }
779         );
780
781         my $ten_days_before = dt_from_string->add( days => -10 );
782         my $ten_days_ahead  = dt_from_string->add( days => 10 );
783         AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
784         $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = NULL, no_auto_renewal_after_hard_limit = NULL');
785         my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
786         is( $latest_auto_renew_date, undef, 'GetLatestAutoRenewDate should return undef if no_auto_renewal_after or no_auto_renewal_after_hard_limit are not defined' );
787         my $five_days_before = dt_from_string->add( days => -5 );
788         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 5, no_auto_renewal_after_hard_limit = NULL');
789         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
790         is( $latest_auto_renew_date->truncate( to => 'minute' ),
791             $five_days_before->truncate( to => 'minute' ),
792             'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
793         );
794         my $five_days_ahead = dt_from_string->add( days => 5 );
795         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 15, no_auto_renewal_after_hard_limit = NULL');
796         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
797         is( $latest_auto_renew_date->truncate( to => 'minute' ),
798             $five_days_ahead->truncate( to => 'minute' ),
799             'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
800         );
801         my $two_days_ahead = dt_from_string->add( days => 2 );
802         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = NULL, no_auto_renewal_after_hard_limit = ?', undef, dt_from_string->add( days => 2 ) );
803         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
804         is( $latest_auto_renew_date->truncate( to => 'day' ),
805             $two_days_ahead->truncate( to => 'day' ),
806             'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
807         );
808         $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 15, no_auto_renewal_after_hard_limit = ?', undef, dt_from_string->add( days => 2 ) );
809         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
810         is( $latest_auto_renew_date->truncate( to => 'day' ),
811             $two_days_ahead->truncate( to => 'day' ),
812             'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
813         );
814
815     };
816
817     # Too many renewals
818
819     # set policy to forbid renewals
820     $dbh->do('UPDATE issuingrules SET norenewalbefore = NULL, renewalsallowed = 0');
821
822     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
823     is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
824     is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
825
826     # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
827     t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
828     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
829
830     C4::Overdues::UpdateFine(
831         {
832             issue_id       => $issue->id(),
833             itemnumber     => $itemnumber,
834             borrowernumber => $renewing_borrower->{borrowernumber},
835             amount         => 15.00,
836             type           => q{},
837             due            => Koha::DateUtils::output_pref($datedue)
838         }
839     );
840
841     my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower->{borrowernumber} })->next();
842     is( $line->accounttype, 'FU', 'Account line type is FU' );
843     is( $line->lastincrement, '15.000000', 'Account line last increment is 15.00' );
844     is( $line->amountoutstanding, '15.000000', 'Account line amount outstanding is 15.00' );
845     is( $line->amount, '15.000000', 'Account line amount is 15.00' );
846     is( $line->issue_id, $issue->id, 'Account line issue id matches' );
847
848     my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
849     is( $offset->type, 'Fine', 'Account offset type is Fine' );
850     is( $offset->amount, '15.000000', 'Account offset amount is 15.00' );
851
852     t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
853     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
854
855     LostItem( $itemnumber, 'test', 1 );
856
857     my $item = Koha::Database->new()->schema()->resultset('Item')->find($itemnumber);
858     ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
859     my $checkout = Koha::Checkouts->find({ itemnumber => $itemnumber });
860     is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
861
862     my $total_due = $dbh->selectrow_array(
863         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
864         undef, $renewing_borrower->{borrowernumber}
865     );
866
867     is( $total_due, '15.000000', 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
868
869     C4::Context->dbh->do("DELETE FROM accountlines");
870
871     C4::Overdues::UpdateFine(
872         {
873             issue_id       => $issue2->id(),
874             itemnumber     => $itemnumber2,
875             borrowernumber => $renewing_borrower->{borrowernumber},
876             amount         => 15.00,
877             type           => q{},
878             due            => Koha::DateUtils::output_pref($datedue)
879         }
880     );
881
882     LostItem( $itemnumber2, 'test', 0 );
883
884     my $item2 = Koha::Database->new()->schema()->resultset('Item')->find($itemnumber2);
885     ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
886     ok( Koha::Checkouts->find({ itemnumber => $itemnumber2 }), 'LostItem called without forced return has checked in the item' );
887
888     $total_due = $dbh->selectrow_array(
889         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
890         undef, $renewing_borrower->{borrowernumber}
891     );
892
893     ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
894
895     my $future = dt_from_string();
896     $future->add( days => 7 );
897     my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
898     ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
899
900     # Users cannot renew any item if there is an overdue item
901     t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
902     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber6);
903     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
904     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber7);
905     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
906
907     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
908     $checkout = Koha::Checkouts->find( { itemnumber => $itemnumber3 } );
909     LostItem( $itemnumber3, 'test', 0 );
910     my $accountline = Koha::Account::Lines->find( { itemnumber => $itemnumber3 } );
911     is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
912
913   }
914
915 {
916     # GetUpcomingDueIssues tests
917     my $barcode  = 'R00000342';
918     my $barcode2 = 'R00000343';
919     my $barcode3 = 'R00000344';
920     my $branch   = $library2->{branchcode};
921
922     #Create another record
923     my $title2 = 'Something is worng here';
924     my ($biblionumber2, $biblioitemnumber2) = add_biblio($title2, 'Anonymous');
925
926     #Create third item
927     AddItem(
928         {
929             homebranch       => $branch,
930             holdingbranch    => $branch,
931             barcode          => $barcode3,
932             itype            => $itemtype
933         },
934         $biblionumber2
935     );
936
937     # Create a borrower
938     my %a_borrower_data = (
939         firstname =>  'Fridolyn',
940         surname => 'SOMERS',
941         categorycode => $patron_category->{categorycode},
942         branchcode => $branch,
943     );
944
945     my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
946     my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
947
948     my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
949     my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
950     my $today = DateTime->today(time_zone => C4::Context->tz());
951
952     my $issue = AddIssue( $a_borrower, $barcode, $yesterday );
953     my $datedue = dt_from_string( $issue->date_due() );
954     my $issue2 = AddIssue( $a_borrower, $barcode2, $two_days_ahead );
955     my $datedue2 = dt_from_string( $issue->date_due() );
956
957     my $upcoming_dues;
958
959     # GetUpcomingDueIssues tests
960     for my $i(0..1) {
961         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
962         is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
963     }
964
965     #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
966     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
967     is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
968
969     for my $i(3..5) {
970         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
971         is ( scalar( @$upcoming_dues ), 1,
972             "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
973     }
974
975     # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
976
977     my $issue3 = AddIssue( $a_borrower, $barcode3, $today );
978
979     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
980     is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
981
982     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
983     is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
984
985     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
986     is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
987
988     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 }  );
989     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
990
991     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
992     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
993
994     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
995     is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
996
997 }
998
999 {
1000     my $barcode  = '1234567890';
1001     my $branch   = $library2->{branchcode};
1002
1003     my ($biblionumber, $biblioitemnumber) = add_biblio();
1004
1005     #Create third item
1006     my ( undef, undef, $itemnumber ) = AddItem(
1007         {
1008             homebranch       => $branch,
1009             holdingbranch    => $branch,
1010             barcode          => $barcode,
1011             itype            => $itemtype
1012         },
1013         $biblionumber
1014     );
1015
1016     # Create a borrower
1017     my %a_borrower_data = (
1018         firstname =>  'Kyle',
1019         surname => 'Hall',
1020         categorycode => $patron_category->{categorycode},
1021         branchcode => $branch,
1022     );
1023
1024     my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1025
1026     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1027     my $issue = AddIssue( $borrower, $barcode );
1028     UpdateFine(
1029         {
1030             issue_id       => $issue->id(),
1031             itemnumber     => $itemnumber,
1032             borrowernumber => $borrowernumber,
1033             amount         => 0,
1034             type           => q{}
1035         }
1036     );
1037
1038     my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $itemnumber );
1039     my $count = $hr->{count};
1040
1041     is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1042 }
1043
1044 {
1045     $dbh->do('DELETE FROM issues');
1046     $dbh->do('DELETE FROM items');
1047     $dbh->do('DELETE FROM issuingrules');
1048     $dbh->do(
1049         q{
1050         INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, maxissueqty, issuelength, lengthunit, renewalsallowed, renewalperiod,
1051                     norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
1052         },
1053         {},
1054         '*', '*', '*', 25,
1055         20,  14,  'days',
1056         1,   7,
1057         undef,  0,
1058         .10, 1
1059     );
1060     my ( $biblionumber, $biblioitemnumber ) = add_biblio();
1061
1062     my $barcode1 = '1234';
1063     my ( undef, undef, $itemnumber1 ) = AddItem(
1064         {
1065             homebranch    => $library2->{branchcode},
1066             holdingbranch => $library2->{branchcode},
1067             barcode       => $barcode1,
1068             itype         => $itemtype
1069         },
1070         $biblionumber
1071     );
1072     my $barcode2 = '4321';
1073     my ( undef, undef, $itemnumber2 ) = AddItem(
1074         {
1075             homebranch    => $library2->{branchcode},
1076             holdingbranch => $library2->{branchcode},
1077             barcode       => $barcode2,
1078             itype         => $itemtype
1079         },
1080         $biblionumber
1081     );
1082
1083     my $borrowernumber1 = Koha::Patron->new({
1084         firstname    => 'Kyle',
1085         surname      => 'Hall',
1086         categorycode => $patron_category->{categorycode},
1087         branchcode   => $library2->{branchcode},
1088     })->store->borrowernumber;
1089     my $borrowernumber2 = Koha::Patron->new({
1090         firstname    => 'Chelsea',
1091         surname      => 'Hall',
1092         categorycode => $patron_category->{categorycode},
1093         branchcode   => $library2->{branchcode},
1094     })->store->borrowernumber;
1095
1096     my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1097     my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1098
1099     my $issue = AddIssue( $borrower1, $barcode1 );
1100
1101     my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1102     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1103
1104     AddReserve(
1105         $library2->{branchcode}, $borrowernumber2, $biblionumber,
1106         '',  1, undef, undef, '',
1107         undef, undef, undef
1108     );
1109
1110     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1111     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1112     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1113     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1114
1115     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1116     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1117     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1118     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1119
1120     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1121     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1122     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1123     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1124
1125     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1126     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1127     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1128     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1129
1130     # Setting item not checked out to be not for loan but holdable
1131     ModItem({ notforloan => -1 }, $biblionumber, $itemnumber2);
1132
1133     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1134     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' );
1135 }
1136
1137 {
1138     # Don't allow renewing onsite checkout
1139     my $barcode  = 'R00000XXX';
1140     my $branch   = $library->{branchcode};
1141
1142     #Create another record
1143     my ($biblionumber, $biblioitemnumber) = add_biblio('A title', 'Anonymous');
1144
1145     my (undef, undef, $itemnumber) = AddItem(
1146         {
1147             homebranch       => $branch,
1148             holdingbranch    => $branch,
1149             barcode          => $barcode,
1150             itype            => $itemtype
1151         },
1152         $biblionumber
1153     );
1154
1155     my $borrowernumber = Koha::Patron->new({
1156         firstname =>  'fn',
1157         surname => 'dn',
1158         categorycode => $patron_category->{categorycode},
1159         branchcode => $branch,
1160     })->store->borrowernumber;
1161
1162     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1163
1164     my $issue = AddIssue( $borrower, $barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1165     my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $itemnumber );
1166     is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1167     is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1168 }
1169
1170 {
1171     my $library = $builder->build({ source => 'Branch' });
1172
1173     my ($biblionumber, $biblioitemnumber) = add_biblio();
1174
1175     my $barcode = 'just a barcode';
1176     my ( undef, undef, $itemnumber ) = AddItem(
1177         {
1178             homebranch       => $library->{branchcode},
1179             holdingbranch    => $library->{branchcode},
1180             barcode          => $barcode,
1181             itype            => $itemtype
1182         },
1183         $biblionumber,
1184     );
1185
1186     my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1187
1188     my $issue = AddIssue( $patron, $barcode );
1189     UpdateFine(
1190         {
1191             issue_id       => $issue->id(),
1192             itemnumber     => $itemnumber,
1193             borrowernumber => $patron->{borrowernumber},
1194             amount         => 1,
1195             type           => q{}
1196         }
1197     );
1198     UpdateFine(
1199         {
1200             issue_id       => $issue->id(),
1201             itemnumber     => $itemnumber,
1202             borrowernumber => $patron->{borrowernumber},
1203             amount         => 2,
1204             type           => q{}
1205         }
1206     );
1207     is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1208 }
1209
1210 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1211     plan tests => 24;
1212
1213     my $homebranch    = $builder->build( { source => 'Branch' } );
1214     my $holdingbranch = $builder->build( { source => 'Branch' } );
1215     my $otherbranch   = $builder->build( { source => 'Branch' } );
1216     my $patron_1      = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1217     my $patron_2      = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1218
1219     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1220     my $item = $builder->build(
1221         {   source => 'Item',
1222             value  => {
1223                 homebranch    => $homebranch->{branchcode},
1224                 holdingbranch => $holdingbranch->{branchcode},
1225                 biblionumber  => $biblioitem->{biblionumber}
1226             }
1227         }
1228     );
1229
1230     set_userenv($holdingbranch);
1231
1232     my $issue = AddIssue( $patron_1->unblessed, $item->{barcode} );
1233     is( ref($issue), 'Koha::Schema::Result::Issue' );    # FIXME Should be Koha::Checkout
1234
1235     my ( $error, $question, $alerts );
1236
1237     # AllowReturnToBranch == anywhere
1238     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1239     ## Test that unknown barcodes don't generate internal server errors
1240     set_userenv($homebranch);
1241     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1242     ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1243     ## Can be issued from homebranch
1244     set_userenv($homebranch);
1245     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1246     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1247     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1248     ## Can be issued from holdingbranch
1249     set_userenv($holdingbranch);
1250     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1251     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1252     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1253     ## Can be issued from another branch
1254     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1255     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1256     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1257
1258     # AllowReturnToBranch == holdingbranch
1259     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1260     ## Cannot be issued from homebranch
1261     set_userenv($homebranch);
1262     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1263     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1264     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1265     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
1266     ## Can be issued from holdinbranch
1267     set_userenv($holdingbranch);
1268     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1269     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1270     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1271     ## Cannot be issued from another branch
1272     set_userenv($otherbranch);
1273     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1274     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1275     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1276     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
1277
1278     # AllowReturnToBranch == homebranch
1279     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1280     ## Can be issued from holdinbranch
1281     set_userenv($homebranch);
1282     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1283     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1284     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1285     ## Cannot be issued from holdinbranch
1286     set_userenv($holdingbranch);
1287     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1288     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1289     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1290     is( $error->{branch_to_return},         $homebranch->{branchcode} );
1291     ## Cannot be issued from holdinbranch
1292     set_userenv($otherbranch);
1293     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1294     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1295     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1296     is( $error->{branch_to_return},         $homebranch->{branchcode} );
1297
1298     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1299 };
1300
1301 subtest 'AddIssue & AllowReturnToBranch' => sub {
1302     plan tests => 9;
1303
1304     my $homebranch    = $builder->build( { source => 'Branch' } );
1305     my $holdingbranch = $builder->build( { source => 'Branch' } );
1306     my $otherbranch   = $builder->build( { source => 'Branch' } );
1307     my $patron_1      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1308     my $patron_2      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1309
1310     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1311     my $item = $builder->build(
1312         {   source => 'Item',
1313             value  => {
1314                 homebranch    => $homebranch->{branchcode},
1315                 holdingbranch => $holdingbranch->{branchcode},
1316                 notforloan    => 0,
1317                 itemlost      => 0,
1318                 withdrawn     => 0,
1319                 biblionumber  => $biblioitem->{biblionumber}
1320             }
1321         }
1322     );
1323
1324     set_userenv($holdingbranch);
1325
1326     my $ref_issue = 'Koha::Schema::Result::Issue'; # FIXME Should be Koha::Checkout
1327     my $issue = AddIssue( $patron_1, $item->{barcode} );
1328
1329     my ( $error, $question, $alerts );
1330
1331     # AllowReturnToBranch == homebranch
1332     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1333     ## Can be issued from homebranch
1334     set_userenv($homebranch);
1335     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1336     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1337     ## Can be issued from holdinbranch
1338     set_userenv($holdingbranch);
1339     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1340     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1341     ## Can be issued from another branch
1342     set_userenv($otherbranch);
1343     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1344     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1345
1346     # AllowReturnToBranch == holdinbranch
1347     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1348     ## Cannot be issued from homebranch
1349     set_userenv($homebranch);
1350     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1351     ## Can be issued from holdingbranch
1352     set_userenv($holdingbranch);
1353     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1354     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1355     ## Cannot be issued from another branch
1356     set_userenv($otherbranch);
1357     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1358
1359     # AllowReturnToBranch == homebranch
1360     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1361     ## Can be issued from homebranch
1362     set_userenv($homebranch);
1363     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1364     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1365     ## Cannot be issued from holdinbranch
1366     set_userenv($holdingbranch);
1367     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1368     ## Cannot be issued from another branch
1369     set_userenv($otherbranch);
1370     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1371     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1372 };
1373
1374 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1375     plan tests => 8;
1376
1377     my $library = $builder->build( { source => 'Branch' } );
1378     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1379
1380     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1381     my $item_1 = $builder->build(
1382         {   source => 'Item',
1383             value  => {
1384                 homebranch    => $library->{branchcode},
1385                 holdingbranch => $library->{branchcode},
1386                 biblionumber  => $biblioitem_1->{biblionumber}
1387             }
1388         }
1389     );
1390     my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1391     my $item_2 = $builder->build(
1392         {   source => 'Item',
1393             value  => {
1394                 homebranch    => $library->{branchcode},
1395                 holdingbranch => $library->{branchcode},
1396                 biblionumber  => $biblioitem_2->{biblionumber}
1397             }
1398         }
1399     );
1400
1401     my ( $error, $question, $alerts );
1402
1403     # Patron cannot issue item_1, they have overdues
1404     my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1405     my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, $yesterday );    # Add an overdue
1406
1407     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1408     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1409     is( keys(%$error) + keys(%$alerts),  0, 'No key for error and alert' . str($error, $question, $alerts) );
1410     is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
1411
1412     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1413     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1414     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1415     is( $error->{USERBLOCKEDOVERDUE},      1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
1416
1417     # Patron cannot issue item_1, they are debarred
1418     my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1419     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
1420     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1421     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1422     is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
1423
1424     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
1425     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1426     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1427     is( $error->{USERBLOCKEDNOENDDATE},    '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
1428 };
1429
1430 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
1431     plan tests => 1;
1432
1433     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1434     my $patron_category_x = $builder->build_object(
1435         {
1436             class => 'Koha::Patron::Categories',
1437             value => { category_type => 'X' }
1438         }
1439     );
1440     my $patron = $builder->build_object(
1441         {
1442             class => 'Koha::Patrons',
1443             value => {
1444                 categorycode  => $patron_category_x->categorycode,
1445                 gonenoaddress => undef,
1446                 lost          => undef,
1447                 debarred      => undef,
1448                 borrowernotes => ""
1449             }
1450         }
1451     );
1452     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1453     my $item_1 = $builder->build(
1454         {
1455             source => 'Item',
1456             value  => {
1457                 homebranch    => $library->branchcode,
1458                 holdingbranch => $library->branchcode,
1459                 biblionumber  => $biblioitem_1->{biblionumber}
1460             }
1461         }
1462     );
1463
1464     my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->{barcode} );
1465     is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
1466
1467     # TODO There are other tests to provide here
1468 };
1469
1470 subtest 'MultipleReserves' => sub {
1471     plan tests => 3;
1472
1473     my $title = 'Silence in the library';
1474     my ($biblionumber, $biblioitemnumber) = add_biblio($title, 'Moffat, Steven');
1475
1476     my $branch = $library2->{branchcode};
1477
1478     my $barcode1 = 'R00110001';
1479     my ( $item_bibnum1, $item_bibitemnum1, $itemnumber1 ) = AddItem(
1480         {
1481             homebranch       => $branch,
1482             holdingbranch    => $branch,
1483             barcode          => $barcode1,
1484             replacementprice => 12.00,
1485             itype            => $itemtype
1486         },
1487         $biblionumber
1488     );
1489
1490     my $barcode2 = 'R00110002';
1491     my ( $item_bibnum2, $item_bibitemnum2, $itemnumber2 ) = AddItem(
1492         {
1493             homebranch       => $branch,
1494             holdingbranch    => $branch,
1495             barcode          => $barcode2,
1496             replacementprice => 12.00,
1497             itype            => $itemtype
1498         },
1499         $biblionumber
1500     );
1501
1502     my $bibitems       = '';
1503     my $priority       = '1';
1504     my $resdate        = undef;
1505     my $expdate        = undef;
1506     my $notes          = '';
1507     my $checkitem      = undef;
1508     my $found          = undef;
1509
1510     my %renewing_borrower_data = (
1511         firstname =>  'John',
1512         surname => 'Renewal',
1513         categorycode => $patron_category->{categorycode},
1514         branchcode => $branch,
1515     );
1516     my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
1517     my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
1518     my $issue = AddIssue( $renewing_borrower, $barcode1);
1519     my $datedue = dt_from_string( $issue->date_due() );
1520     is (defined $issue->date_due(), 1, "item 1 checked out");
1521     my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $itemnumber1 })->borrowernumber;
1522
1523     my %reserving_borrower_data1 = (
1524         firstname =>  'Katrin',
1525         surname => 'Reservation',
1526         categorycode => $patron_category->{categorycode},
1527         branchcode => $branch,
1528     );
1529     my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
1530     AddReserve(
1531         $branch, $reserving_borrowernumber1, $biblionumber,
1532         $bibitems,  $priority, $resdate, $expdate, $notes,
1533         $title, $checkitem, $found
1534     );
1535
1536     my %reserving_borrower_data2 = (
1537         firstname =>  'Kirk',
1538         surname => 'Reservation',
1539         categorycode => $patron_category->{categorycode},
1540         branchcode => $branch,
1541     );
1542     my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
1543     AddReserve(
1544         $branch, $reserving_borrowernumber2, $biblionumber,
1545         $bibitems,  $priority, $resdate, $expdate, $notes,
1546         $title, $checkitem, $found
1547     );
1548
1549     {
1550         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber1, 1);
1551         is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
1552     }
1553
1554     my $barcode3 = 'R00110003';
1555     my ( $item_bibnum3, $item_bibitemnum3, $itemnumber3 ) = AddItem(
1556         {
1557             homebranch       => $branch,
1558             holdingbranch    => $branch,
1559             barcode          => $barcode3,
1560             replacementprice => 12.00,
1561             itype            => $itemtype
1562         },
1563         $biblionumber
1564     );
1565
1566     {
1567         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber1, 1);
1568         is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
1569     }
1570 };
1571
1572 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
1573     plan tests => 5;
1574
1575     my $library = $builder->build( { source => 'Branch' } );
1576     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1577
1578     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1579     my $biblionumber = $biblioitem->{biblionumber};
1580     my $item_1 = $builder->build(
1581         {   source => 'Item',
1582             value  => {
1583                 homebranch    => $library->{branchcode},
1584                 holdingbranch => $library->{branchcode},
1585                 biblionumber  => $biblionumber,
1586             }
1587         }
1588     );
1589     my $item_2 = $builder->build(
1590         {   source => 'Item',
1591             value  => {
1592                 homebranch    => $library->{branchcode},
1593                 holdingbranch => $library->{branchcode},
1594                 biblionumber  => $biblionumber,
1595             }
1596         }
1597     );
1598
1599     my ( $error, $question, $alerts );
1600     my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, dt_from_string->add( days => 1 ) );
1601
1602     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1603     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1604     is( keys(%$error) + keys(%$alerts),  0, 'No error or alert should be raised' . str($error, $question, $alerts) );
1605     is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' . str($error, $question, $alerts) );
1606
1607     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1608     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1609     is( keys(%$error) + keys(%$question) + keys(%$alerts),  0, 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1' . str($error, $question, $alerts) );
1610
1611     # Add a subscription
1612     Koha::Subscription->new({ biblionumber => $biblionumber })->store;
1613
1614     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1615     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1616     is( keys(%$error) + keys(%$question) + keys(%$alerts),  0, 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription' . str($error, $question, $alerts) );
1617
1618     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1619     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1620     is( keys(%$error) + keys(%$question) + keys(%$alerts),  0, 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription' . str($error, $question, $alerts) );
1621 };
1622
1623 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
1624     plan tests => 8;
1625
1626     my $library = $builder->build( { source => 'Branch' } );
1627     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1628
1629     # Add 2 items
1630     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1631     my $item_1 = $builder->build(
1632         {
1633             source => 'Item',
1634             value  => {
1635                 homebranch    => $library->{branchcode},
1636                 holdingbranch => $library->{branchcode},
1637                 notforloan    => 0,
1638                 itemlost      => 0,
1639                 withdrawn     => 0,
1640                 biblionumber  => $biblioitem_1->{biblionumber}
1641             }
1642         }
1643     );
1644     my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1645     my $item_2 = $builder->build(
1646         {
1647             source => 'Item',
1648             value  => {
1649                 homebranch    => $library->{branchcode},
1650                 holdingbranch => $library->{branchcode},
1651                 notforloan    => 0,
1652                 itemlost      => 0,
1653                 withdrawn     => 0,
1654                 biblionumber  => $biblioitem_2->{biblionumber}
1655             }
1656         }
1657     );
1658
1659     # And the issuing rule
1660     Koha::IssuingRules->search->delete;
1661     my $rule = Koha::IssuingRule->new(
1662         {
1663             categorycode => '*',
1664             itemtype     => '*',
1665             branchcode   => '*',
1666             maxissueqty  => 99,
1667             issuelength  => 1,
1668             firstremind  => 1,        # 1 day of grace
1669             finedays     => 2,        # 2 days of fine per day of overdue
1670             lengthunit   => 'days',
1671         }
1672     );
1673     $rule->store();
1674
1675     # Patron cannot issue item_1, they have overdues
1676     my $five_days_ago = dt_from_string->subtract( days => 5 );
1677     my $ten_days_ago  = dt_from_string->subtract( days => 10 );
1678     AddIssue( $patron, $item_1->{barcode}, $five_days_ago );    # Add an overdue
1679     AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1680       ;    # Add another overdue
1681
1682     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
1683     AddReturn( $item_1->{barcode}, $library->{branchcode},
1684         undef, undef, dt_from_string );
1685     my $debarments = Koha::Patron::Debarments::GetDebarments(
1686         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1687     is( scalar(@$debarments), 1 );
1688
1689     # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
1690     # Same for the others
1691     my $expected_expiration = output_pref(
1692         {
1693             dt         => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1694             dateformat => 'sql',
1695             dateonly   => 1
1696         }
1697     );
1698     is( $debarments->[0]->{expiration}, $expected_expiration );
1699
1700     AddReturn( $item_2->{barcode}, $library->{branchcode},
1701         undef, undef, dt_from_string );
1702     $debarments = Koha::Patron::Debarments::GetDebarments(
1703         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1704     is( scalar(@$debarments), 1 );
1705     $expected_expiration = output_pref(
1706         {
1707             dt         => dt_from_string->add( days => ( 10 - 1 ) * 2 ),
1708             dateformat => 'sql',
1709             dateonly   => 1
1710         }
1711     );
1712     is( $debarments->[0]->{expiration}, $expected_expiration );
1713
1714     Koha::Patron::Debarments::DelUniqueDebarment(
1715         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1716
1717     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
1718     AddIssue( $patron, $item_1->{barcode}, $five_days_ago );    # Add an overdue
1719     AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1720       ;    # Add another overdue
1721     AddReturn( $item_1->{barcode}, $library->{branchcode},
1722         undef, undef, dt_from_string );
1723     $debarments = Koha::Patron::Debarments::GetDebarments(
1724         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1725     is( scalar(@$debarments), 1 );
1726     $expected_expiration = output_pref(
1727         {
1728             dt         => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1729             dateformat => 'sql',
1730             dateonly   => 1
1731         }
1732     );
1733     is( $debarments->[0]->{expiration}, $expected_expiration );
1734
1735     AddReturn( $item_2->{barcode}, $library->{branchcode},
1736         undef, undef, dt_from_string );
1737     $debarments = Koha::Patron::Debarments::GetDebarments(
1738         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1739     is( scalar(@$debarments), 1 );
1740     $expected_expiration = output_pref(
1741         {
1742             dt => dt_from_string->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
1743             dateformat => 'sql',
1744             dateonly   => 1
1745         }
1746     );
1747     is( $debarments->[0]->{expiration}, $expected_expiration );
1748 };
1749
1750 subtest 'AddReturn + suspension_chargeperiod' => sub {
1751     plan tests => 21;
1752
1753     my $library = $builder->build( { source => 'Branch' } );
1754     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1755
1756     # Add 2 items
1757     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1758     my $item_1 = $builder->build(
1759         {
1760             source => 'Item',
1761             value  => {
1762                 homebranch    => $library->{branchcode},
1763                 holdingbranch => $library->{branchcode},
1764                 notforloan    => 0,
1765                 itemlost      => 0,
1766                 withdrawn     => 0,
1767                 biblionumber  => $biblioitem_1->{biblionumber}
1768             }
1769         }
1770     );
1771
1772     # And the issuing rule
1773     Koha::IssuingRules->search->delete;
1774     my $rule = Koha::IssuingRule->new(
1775         {
1776             categorycode => '*',
1777             itemtype     => '*',
1778             branchcode   => '*',
1779             maxissueqty  => 99,
1780             issuelength  => 1,
1781             firstremind  => 0,        # 0 day of grace
1782             finedays     => 2,        # 2 days of fine per day of overdue
1783             suspension_chargeperiod => 1,
1784             lengthunit   => 'days',
1785         }
1786     );
1787     $rule->store();
1788
1789     my $five_days_ago = dt_from_string->subtract( days => 5 );
1790     # We want to charge 2 days every day, without grace
1791     # With 5 days of overdue: 5 * Z
1792     my $expected_expiration = dt_from_string->add( days => ( 5 * 2 ) / 1 );
1793     test_debarment_on_checkout(
1794         {
1795             item            => $item_1,
1796             library         => $library,
1797             patron          => $patron,
1798             due_date        => $five_days_ago,
1799             expiration_date => $expected_expiration,
1800         }
1801     );
1802
1803     # We want to charge 2 days every 2 days, without grace
1804     # With 5 days of overdue: (5 * 2) / 2
1805     $rule->suspension_chargeperiod(2)->store;
1806     $expected_expiration = dt_from_string->add( days => floor( 5 * 2 ) / 2 );
1807     test_debarment_on_checkout(
1808         {
1809             item            => $item_1,
1810             library         => $library,
1811             patron          => $patron,
1812             due_date        => $five_days_ago,
1813             expiration_date => $expected_expiration,
1814         }
1815     );
1816
1817     # We want to charge 2 days every 3 days, with 1 day of grace
1818     # With 5 days of overdue: ((5-1) / 3 ) * 2
1819     $rule->suspension_chargeperiod(3)->store;
1820     $rule->firstremind(1)->store;
1821     $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
1822     test_debarment_on_checkout(
1823         {
1824             item            => $item_1,
1825             library         => $library,
1826             patron          => $patron,
1827             due_date        => $five_days_ago,
1828             expiration_date => $expected_expiration,
1829         }
1830     );
1831
1832     # Use finesCalendar to know if holiday must be skipped to calculate the due date
1833     # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
1834     $rule->finedays(2)->store;
1835     $rule->suspension_chargeperiod(1)->store;
1836     $rule->firstremind(0)->store;
1837     t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
1838
1839     # Adding a holiday 2 days ago
1840     my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
1841     my $two_days_ago = dt_from_string->subtract( days => 2 );
1842     $calendar->insert_single_holiday(
1843         day             => $two_days_ago->day,
1844         month           => $two_days_ago->month,
1845         year            => $two_days_ago->year,
1846         title           => 'holidayTest-2d',
1847         description     => 'holidayDesc 2 days ago'
1848     );
1849     # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
1850     $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
1851     test_debarment_on_checkout(
1852         {
1853             item            => $item_1,
1854             library         => $library,
1855             patron          => $patron,
1856             due_date        => $five_days_ago,
1857             expiration_date => $expected_expiration,
1858         }
1859     );
1860
1861     # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
1862     my $two_days_ahead = dt_from_string->add( days => 2 );
1863     $calendar->insert_single_holiday(
1864         day             => $two_days_ahead->day,
1865         month           => $two_days_ahead->month,
1866         year            => $two_days_ahead->year,
1867         title           => 'holidayTest+2d',
1868         description     => 'holidayDesc 2 days ahead'
1869     );
1870
1871     # Same as above, but we should skip D+2
1872     $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
1873     test_debarment_on_checkout(
1874         {
1875             item            => $item_1,
1876             library         => $library,
1877             patron          => $patron,
1878             due_date        => $five_days_ago,
1879             expiration_date => $expected_expiration,
1880         }
1881     );
1882
1883     # Adding another holiday, day of expiration date
1884     my $expected_expiration_dt = dt_from_string($expected_expiration);
1885     $calendar->insert_single_holiday(
1886         day             => $expected_expiration_dt->day,
1887         month           => $expected_expiration_dt->month,
1888         year            => $expected_expiration_dt->year,
1889         title           => 'holidayTest_exp',
1890         description     => 'holidayDesc on expiration date'
1891     );
1892     # Expiration date will be the day after
1893     test_debarment_on_checkout(
1894         {
1895             item            => $item_1,
1896             library         => $library,
1897             patron          => $patron,
1898             due_date        => $five_days_ago,
1899             expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
1900         }
1901     );
1902
1903     test_debarment_on_checkout(
1904         {
1905             item            => $item_1,
1906             library         => $library,
1907             patron          => $patron,
1908             return_date     => dt_from_string->add(days => 5),
1909             expiration_date => dt_from_string->add(days => 5 + (5 * 2 - 1) ),
1910         }
1911     );
1912 };
1913
1914 subtest 'AddReturn | is_overdue' => sub {
1915     plan tests => 5;
1916
1917     t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
1918     t::lib::Mocks::mock_preference('finesMode', 'production');
1919     t::lib::Mocks::mock_preference('MaxFine', '100');
1920
1921     my $library = $builder->build( { source => 'Branch' } );
1922     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1923
1924     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1925     my $item = $builder->build(
1926         {
1927             source => 'Item',
1928             value  => {
1929                 homebranch    => $library->{branchcode},
1930                 holdingbranch => $library->{branchcode},
1931                 notforloan    => 0,
1932                 itemlost      => 0,
1933                 withdrawn     => 0,
1934                 biblionumber  => $biblioitem->{biblionumber},
1935             }
1936         }
1937     );
1938
1939     Koha::IssuingRules->search->delete;
1940     my $rule = Koha::IssuingRule->new(
1941         {
1942             categorycode => '*',
1943             itemtype     => '*',
1944             branchcode   => '*',
1945             maxissueqty  => 99,
1946             issuelength  => 6,
1947             lengthunit   => 'days',
1948             fine         => 1, # Charge 1 every day of overdue
1949             chargeperiod => 1,
1950         }
1951     );
1952     $rule->store();
1953
1954     my $one_day_ago   = dt_from_string->subtract( days => 1 );
1955     my $five_days_ago = dt_from_string->subtract( days => 5 );
1956     my $ten_days_ago  = dt_from_string->subtract( days => 10 );
1957     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1958
1959     # No date specify, today will be used
1960     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1961     AddReturn( $item->{barcode}, $library->{branchcode} );
1962     is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
1963     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1964
1965     # specify return date 5 days before => no overdue
1966     AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
1967     AddReturn( $item->{barcode}, $library->{branchcode}, undef, undef, $ten_days_ago );
1968     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
1969     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1970
1971     # specify return date 5 days later => overdue
1972     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1973     AddReturn( $item->{barcode}, $library->{branchcode}, undef, undef, $five_days_ago );
1974     is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
1975     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1976
1977     # specify dropbox date 5 days before => no overdue
1978     AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
1979     AddReturn( $item->{barcode}, $library->{branchcode}, undef, 1, undef, $ten_days_ago );
1980     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
1981     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1982
1983     # specify dropbox date 5 days later => overdue, or... not
1984     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1985     AddReturn( $item->{barcode}, $library->{branchcode}, undef, 1, undef, $five_days_ago );
1986     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue in dropbox mode' ); # FIXME? This is weird, the FU fine is created ( _CalculateAndUpdateFine > C4::Overdues::UpdateFine ) then remove later (in _FixOverduesOnReturn). Looks like it is a feature
1987     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1988 };
1989
1990 subtest '_FixAccountForLostAndReturned' => sub {
1991
1992     plan tests => 4;
1993
1994     t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
1995     t::lib::Mocks::mock_preference( 'WhenLostForgiveFine',          0 );
1996
1997     my $processfee_amount  = 20;
1998     my $replacement_amount = 99.00;
1999     my $item_type          = $builder->build_object(
2000         {   class => 'Koha::ItemTypes',
2001             value => {
2002                 notforloan         => undef,
2003                 rentalcharge       => 0,
2004                 defaultreplacecost => undef,
2005                 processfee         => $processfee_amount
2006             }
2007         }
2008     );
2009     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2010
2011     # Generate test biblio
2012     my $title = 'Koha for Dummies';
2013     my ( $biblionumber, $biblioitemnumber ) = add_biblio( $title, 'Hall, Daria' );
2014
2015     subtest 'Full write-off tests' => sub {
2016
2017         plan tests => 10;
2018
2019         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2020         my $barcode = 'KD123456789';
2021
2022         my ( undef, undef, $item_id ) = AddItem(
2023             {   homebranch       => $library->branchcode,
2024                 holdingbranch    => $library->branchcode,
2025                 barcode          => $barcode,
2026                 replacementprice => $replacement_amount,
2027                 itype            => $item_type->itemtype
2028             },
2029             $biblionumber
2030         );
2031
2032         AddIssue( $patron->unblessed, $barcode );
2033
2034         # Simulate item marked as lost
2035         ModItem( { itemlost => 3 }, $biblionumber, $item_id );
2036         LostItem( $item_id, 1 );
2037
2038         my $processing_fee_lines = Koha::Account::Lines->search(
2039             { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'PF' } );
2040         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2041         my $processing_fee_line = $processing_fee_lines->next;
2042         is( $processing_fee_line->amount + 0,
2043             $processfee_amount, 'The right PF amount is generated' );
2044         is( $processing_fee_line->amountoutstanding + 0,
2045             $processfee_amount, 'The right PF amountoutstanding is generated' );
2046
2047         my $lost_fee_lines = Koha::Account::Lines->search(
2048             { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'L' } );
2049         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2050         my $lost_fee_line = $lost_fee_lines->next;
2051         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2052         is( $lost_fee_line->amountoutstanding + 0,
2053             $replacement_amount, 'The right L amountountstanding is generated' );
2054
2055         my $account = $patron->account;
2056         my $debts   = $account->outstanding_debits;
2057
2058         # Write off the debt
2059         my $credit = $account->add_credit(
2060             {   amount => $account->balance,
2061                 type   => 'writeoff'
2062             }
2063         );
2064         $credit->apply( { debits => $debts, offset_type => 'Writeoff' } );
2065
2066         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item_id, $patron->id );
2067         is( $credit_return_id, undef, 'No CR account line added' );
2068
2069         $lost_fee_line->discard_changes; # reload from DB
2070         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2071         is( $lost_fee_line->accounttype,
2072             'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2073
2074         is( $patron->account->balance, -0, 'The patron balance is 0, everything was written off' );
2075     };
2076
2077     subtest 'Full payment tests' => sub {
2078
2079         plan tests => 12;
2080
2081         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2082         my $barcode = 'KD123456790';
2083
2084         my ( undef, undef, $item_id ) = AddItem(
2085             {   homebranch       => $library->branchcode,
2086                 holdingbranch    => $library->branchcode,
2087                 barcode          => $barcode,
2088                 replacementprice => $replacement_amount,
2089                 itype            => $item_type->itemtype
2090             },
2091             $biblionumber
2092         );
2093
2094         AddIssue( $patron->unblessed, $barcode );
2095
2096         # Simulate item marked as lost
2097         ModItem( { itemlost => 1 }, $biblionumber, $item_id );
2098         LostItem( $item_id, 1 );
2099
2100         my $processing_fee_lines = Koha::Account::Lines->search(
2101             { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'PF' } );
2102         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2103         my $processing_fee_line = $processing_fee_lines->next;
2104         is( $processing_fee_line->amount + 0,
2105             $processfee_amount, 'The right PF amount is generated' );
2106         is( $processing_fee_line->amountoutstanding + 0,
2107             $processfee_amount, 'The right PF amountoutstanding is generated' );
2108
2109         my $lost_fee_lines = Koha::Account::Lines->search(
2110             { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'L' } );
2111         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2112         my $lost_fee_line = $lost_fee_lines->next;
2113         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2114         is( $lost_fee_line->amountoutstanding + 0,
2115             $replacement_amount, 'The right L amountountstanding is generated' );
2116
2117         my $account = $patron->account;
2118         my $debts   = $account->outstanding_debits;
2119
2120         # Write off the debt
2121         my $credit = $account->add_credit(
2122             {   amount => $account->balance,
2123                 type   => 'payment'
2124             }
2125         );
2126         $credit->apply( { debits => $debts, offset_type => 'Payment' } );
2127
2128         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item_id, $patron->id );
2129         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2130
2131         is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2132         is( $credit_return->amount + 0,
2133             -99.00, 'The account line of type CR has an amount of -99' );
2134         is( $credit_return->amountoutstanding + 0,
2135             -99.00, 'The account line of type CR has an amountoutstanding of -99' );
2136
2137         $lost_fee_line->discard_changes;
2138         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2139         is( $lost_fee_line->accounttype,
2140             'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2141
2142         is( $patron->account->balance,
2143             -99, 'The patron balance is -99, a credit that equals the lost fee payment' );
2144     };
2145
2146     subtest 'Test without payment or write off' => sub {
2147
2148         plan tests => 10;
2149
2150         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2151         my $barcode = 'KD123456791';
2152
2153         my ( undef, undef, $item_id ) = AddItem(
2154             {   homebranch       => $library->branchcode,
2155                 holdingbranch    => $library->branchcode,
2156                 barcode          => $barcode,
2157                 replacementprice => $replacement_amount,
2158                 itype            => $item_type->itemtype
2159             },
2160             $biblionumber
2161         );
2162
2163         AddIssue( $patron->unblessed, $barcode );
2164
2165         # Simulate item marked as lost
2166         ModItem( { itemlost => 3 }, $biblionumber, $item_id );
2167         LostItem( $item_id, 1 );
2168
2169         my $processing_fee_lines = Koha::Account::Lines->search(
2170             { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'PF' } );
2171         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2172         my $processing_fee_line = $processing_fee_lines->next;
2173         is( $processing_fee_line->amount + 0,
2174             $processfee_amount, 'The right PF amount is generated' );
2175         is( $processing_fee_line->amountoutstanding + 0,
2176             $processfee_amount, 'The right PF amountoutstanding is generated' );
2177
2178         my $lost_fee_lines = Koha::Account::Lines->search(
2179             { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'L' } );
2180         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2181         my $lost_fee_line = $lost_fee_lines->next;
2182         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2183         is( $lost_fee_line->amountoutstanding + 0,
2184             $replacement_amount, 'The right L amountountstanding is generated' );
2185
2186         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item_id, $patron->id );
2187         is( $credit_return_id, undef, 'No CR account line added' );
2188
2189         $lost_fee_line->discard_changes;
2190         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2191         is( $lost_fee_line->accounttype, 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2192
2193         is( $patron->account->balance, 20, 'The patron balance is 20, still owes the processing fee' );
2194     };
2195
2196     subtest 'Test with partial payement and write off, and remaining debt' => sub {
2197
2198         plan tests => 15;
2199
2200         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2201         my $barcode = 'KD123456792';
2202
2203         my ( undef, undef, $item_id ) = AddItem(
2204             {   homebranch       => $library->branchcode,
2205                 holdingbranch    => $library->branchcode,
2206                 barcode          => $barcode,
2207                 replacementprice => $replacement_amount,
2208                 itype            => $item_type->itemtype
2209             },
2210             $biblionumber
2211         );
2212
2213         AddIssue( $patron->unblessed, $barcode );
2214
2215         # Simulate item marked as lost
2216         ModItem( { itemlost => 1 }, $biblionumber, $item_id );
2217         LostItem( $item_id, 1 );
2218
2219         my $processing_fee_lines = Koha::Account::Lines->search(
2220             { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'PF' } );
2221         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2222         my $processing_fee_line = $processing_fee_lines->next;
2223         is( $processing_fee_line->amount + 0,
2224             $processfee_amount, 'The right PF amount is generated' );
2225         is( $processing_fee_line->amountoutstanding + 0,
2226             $processfee_amount, 'The right PF amountoutstanding is generated' );
2227
2228         my $lost_fee_lines = Koha::Account::Lines->search(
2229             { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'L' } );
2230         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2231         my $lost_fee_line = $lost_fee_lines->next;
2232         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2233         is( $lost_fee_line->amountoutstanding + 0,
2234             $replacement_amount, 'The right L amountountstanding is generated' );
2235
2236         my $account = $patron->account;
2237         is( $account->balance, $processfee_amount + $replacement_amount, 'Balance is PF + L' );
2238
2239         # Partially pay fee
2240         my $payment_amount = 27;
2241         my $payment        = $account->add_credit(
2242             {   amount => $payment_amount,
2243                 type   => 'payment'
2244             }
2245         );
2246
2247         $payment->apply( { debits => $lost_fee_lines->reset, offset_type => 'Payment' } );
2248
2249         # Partially write off fee
2250         my $write_off_amount = 25;
2251         my $write_off        = $account->add_credit(
2252             {   amount => $write_off_amount,
2253                 type   => 'writeoff'
2254             }
2255         );
2256         $write_off->apply( { debits => $lost_fee_lines->reset, offset_type => 'Writeoff' } );
2257
2258         is( $account->balance,
2259             $processfee_amount + $replacement_amount - $payment_amount - $write_off_amount,
2260             'Payment and write off applied'
2261         );
2262
2263         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item_id, $patron->id );
2264         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2265
2266         is( $account->balance, $processfee_amount - $payment_amount, 'Balance is PF - payment (CR)' );
2267
2268         is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2269         is( $credit_return->amount + 0,
2270             $payment_amount * -1,
2271             'The account line of type CR has an amount equal to the payment'
2272         );
2273         is( $credit_return->amountoutstanding + 0,
2274             $payment_amount * -1,
2275             'The account line of type CR has an amountoutstanding equal to the payment'
2276         );
2277
2278         $lost_fee_line->discard_changes;
2279         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2280         is( $lost_fee_line->accounttype,
2281             'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2282
2283         is( $account->balance,
2284             $processfee_amount - $payment_amount,
2285             'The patron balance is the difference between the PF and the credit'
2286         );
2287     };
2288 };
2289
2290 subtest '_FixOverduesOnReturn' => sub {
2291     plan tests => 6;
2292
2293     # Generate test biblio
2294     my $title  = 'Koha for Dummies';
2295     my ( $biblionumber, $biblioitemnumber ) = add_biblio($title, 'Hall, Kylie');
2296
2297     my $barcode = 'KD987654321';
2298     my $branchcode  = $library2->{branchcode};
2299
2300     my ( $item_bibnum, $item_bibitemnum, $itemnumber ) = AddItem(
2301         {
2302             homebranch       => $branchcode,
2303             holdingbranch    => $branchcode,
2304             barcode          => $barcode,
2305             replacementprice => 99.00,
2306             itype            => $itemtype
2307         },
2308         $biblionumber
2309     );
2310
2311     my $patron = $builder->build( { source => 'Borrower' } );
2312
2313     ## Start with basic call, should just close out the open fine
2314     my $accountline = Koha::Account::Line->new(
2315         {
2316             borrowernumber => $patron->{borrowernumber},
2317             accounttype    => 'FU',
2318             itemnumber     => $itemnumber,
2319             amount => 99.00,
2320             amountoutstanding => 99.00,
2321             lastincrement => 9.00,
2322         }
2323     )->store();
2324
2325     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $itemnumber );
2326
2327     $accountline->_result()->discard_changes();
2328
2329     is( $accountline->amountoutstanding, '99.000000', 'Fine has the same amount outstanding as previously' );
2330     is( $accountline->accounttype, 'F', 'Open fine ( account type FU ) has been closed out ( account type F )');
2331
2332
2333     ## Run again, with exemptfine enabled
2334     $accountline->set(
2335         {
2336             accounttype    => 'FU',
2337             amountoutstanding => 99.00,
2338         }
2339     )->store();
2340
2341     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $itemnumber, 1 );
2342
2343     $accountline->_result()->discard_changes();
2344
2345     is( $accountline->amountoutstanding + 0, 0, 'Fine has been reduced to 0' );
2346     is( $accountline->accounttype, 'FFOR', 'Open fine ( account type FU ) has been set to fine forgiven ( account type FFOR )');
2347
2348     ## Run again, with dropbox mode enabled
2349     $accountline->set(
2350         {
2351             accounttype    => 'FU',
2352             amountoutstanding => 99.00,
2353         }
2354     )->store();
2355
2356     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $itemnumber, 0, 1 );
2357
2358     $accountline->_result()->discard_changes();
2359
2360     is( $accountline->amountoutstanding + 0, 90, 'Fine has been reduced to 90' );
2361     is( $accountline->accounttype, 'F', 'Open fine ( account type FU ) has been closed out ( account type F )');
2362 };
2363
2364 subtest 'Set waiting flag' => sub {
2365     plan tests => 4;
2366
2367     my $library_1 = $builder->build( { source => 'Branch' } );
2368     my $patron_1  = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2369     my $library_2 = $builder->build( { source => 'Branch' } );
2370     my $patron_2  = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2371
2372     my $biblio = $builder->build( { source => 'Biblio' } );
2373     my $biblioitem = $builder->build( { source => 'Biblioitem', value => { biblionumber => $biblio->{biblionumber} } } );
2374
2375     my $item = $builder->build(
2376         {
2377             source => 'Item',
2378             value  => {
2379                 homebranch    => $library_1->{branchcode},
2380                 holdingbranch => $library_1->{branchcode},
2381                 notforloan    => 0,
2382                 itemlost      => 0,
2383                 withdrawn     => 0,
2384                 biblionumber  => $biblioitem->{biblionumber},
2385             }
2386         }
2387     );
2388
2389     set_userenv( $library_2 );
2390     my $reserve_id = AddReserve(
2391         $library_2->{branchcode}, $patron_2->{borrowernumber}, $biblioitem->{biblionumber},
2392         '', 1, undef, undef, '', undef, $item->{itemnumber},
2393     );
2394
2395     set_userenv( $library_1 );
2396     my $do_transfer = 1;
2397     my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
2398     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2399     my $hold = Koha::Holds->find( $reserve_id );
2400     is( $hold->found, 'T', 'Hold is in transit' );
2401
2402     my ( $status ) = CheckReserves($item->{itemnumber});
2403     is( $status, 'Reserved', 'Hold is not waiting yet');
2404
2405     set_userenv( $library_2 );
2406     $do_transfer = 0;
2407     AddReturn( $item->{barcode}, $library_2->{branchcode} );
2408     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2409     $hold = Koha::Holds->find( $reserve_id );
2410     is( $hold->found, 'W', 'Hold is waiting' );
2411     ( $status ) = CheckReserves($item->{itemnumber});
2412     is( $status, 'Waiting', 'Now the hold is waiting');
2413 };
2414
2415 subtest 'CanBookBeIssued | is_overdue' => sub {
2416     plan tests => 3;
2417
2418     # Set a simple circ policy
2419     $dbh->do('DELETE FROM issuingrules');
2420     $dbh->do(
2421     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
2422                                     maxissueqty, issuelength, lengthunit,
2423                                     renewalsallowed, renewalperiod,
2424                                     norenewalbefore, auto_renew,
2425                                     fine, chargeperiod)
2426           VALUES (?, ?, ?, ?,
2427                   ?, ?, ?,
2428                   ?, ?,
2429                   ?, ?,
2430                   ?, ?
2431                  )
2432         },
2433         {},
2434         '*',   '*', '*', 25,
2435         1,     14,  'days',
2436         1,     7,
2437         undef, 0,
2438         .10,   1
2439     );
2440
2441     my $five_days_go = output_pref({ dt => dt_from_string->add( days => 5 ), dateonly => 1});
2442     my $ten_days_go  = output_pref({ dt => dt_from_string->add( days => 10), dateonly => 1 });
2443     my $library = $builder->build( { source => 'Branch' } );
2444     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2445
2446     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
2447     my $item = $builder->build(
2448         {
2449             source => 'Item',
2450             value  => {
2451                 homebranch    => $library->{branchcode},
2452                 holdingbranch => $library->{branchcode},
2453                 notforloan    => 0,
2454                 itemlost      => 0,
2455                 withdrawn     => 0,
2456                 biblionumber  => $biblioitem->{biblionumber},
2457             }
2458         }
2459     );
2460
2461     my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $five_days_go ); # date due was 10d ago
2462     my $actualissue = Koha::Checkouts->find( { itemnumber => $item->{itemnumber} } );
2463     is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
2464     my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->{barcode},$ten_days_go, undef, undef, undef);
2465     is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
2466     is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
2467 };
2468
2469 subtest 'ItemsDeniedRenewal preference' => sub {
2470     plan tests => 18;
2471
2472     C4::Context->set_preference('ItemsDeniedRenewal','');
2473
2474     my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
2475     $dbh->do(
2476         q{
2477         INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, maxissueqty, issuelength, lengthunit, renewalsallowed, renewalperiod,
2478                     norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
2479         },
2480         {},
2481         '*', $idr_lib->branchcode, '*', 25,
2482         20,  14,  'days',
2483         10,   7,
2484         undef,  0,
2485         .10, 1
2486     );
2487
2488     my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
2489         homebranch => $idr_lib->branchcode,
2490         withdrawn => 1,
2491         itype => 'HIDE',
2492         location => 'PROC',
2493         itemcallnumber => undef,
2494         itemnotes => "",
2495         }
2496     });
2497     my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
2498         homebranch => $idr_lib->branchcode,
2499         withdrawn => 0,
2500         itype => 'NOHIDE',
2501         location => 'NOPROC'
2502         }
2503     });
2504
2505     my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
2506         branchcode => $idr_lib->branchcode,
2507         }
2508     });
2509     my $future = dt_from_string->add( days => 1 );
2510     my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
2511         returndate => undef,
2512         renewals => 0,
2513         auto_renew => 0,
2514         borrowernumber => $idr_borrower->borrowernumber,
2515         itemnumber => $deny_book->itemnumber,
2516         onsite_checkout => 0,
2517         date_due => $future,
2518         }
2519     });
2520     my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
2521         returndate => undef,
2522         renewals => 0,
2523         auto_renew => 0,
2524         borrowernumber => $idr_borrower->borrowernumber,
2525         itemnumber => $allow_book->itemnumber,
2526         onsite_checkout => 0,
2527         date_due => $future,
2528         }
2529     });
2530
2531     my $idr_rules;
2532
2533     my ( $idr_mayrenew, $idr_error ) =
2534     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2535     is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
2536     is( $idr_error, undef, 'Renewal allowed when no rules' );
2537
2538     $idr_rules="withdrawn: [1]";
2539
2540     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2541     ( $idr_mayrenew, $idr_error ) =
2542     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2543     is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
2544     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
2545     ( $idr_mayrenew, $idr_error ) =
2546     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2547     is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
2548     is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
2549
2550     $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
2551
2552     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2553     ( $idr_mayrenew, $idr_error ) =
2554     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2555     is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
2556     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
2557     ( $idr_mayrenew, $idr_error ) =
2558     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2559     is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
2560     is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
2561
2562     $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
2563
2564     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2565     ( $idr_mayrenew, $idr_error ) =
2566     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2567     is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
2568     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
2569     ( $idr_mayrenew, $idr_error ) =
2570     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2571     is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
2572     is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
2573
2574     $idr_rules="itemcallnumber: [NULL]";
2575     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2576     ( $idr_mayrenew, $idr_error ) =
2577     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2578     is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
2579     $idr_rules="itemcallnumber: ['']";
2580     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2581     ( $idr_mayrenew, $idr_error ) =
2582     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2583     is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
2584
2585     $idr_rules="itemnotes: [NULL]";
2586     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2587     ( $idr_mayrenew, $idr_error ) =
2588     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2589     is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
2590     $idr_rules="itemnotes: ['']";
2591     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2592     ( $idr_mayrenew, $idr_error ) =
2593     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2594     is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
2595 };
2596
2597 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
2598     plan tests => 2;
2599
2600     t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
2601     my $library = $builder->build( { source => 'Branch' } );
2602     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
2603
2604     my $itemtype = $builder->build(
2605         {
2606             source => 'Itemtype',
2607             value  => { notforloan => undef, }
2608         }
2609     );
2610
2611     my $biblioitem = $builder->build( { source => 'Biblioitem', value => { itemtype => $itemtype->{itemtype} } } );
2612     my $item = $builder->build_object(
2613         {
2614             class => 'Koha::Items',
2615             value  => {
2616                 homebranch    => $library->{branchcode},
2617                 holdingbranch => $library->{branchcode},
2618                 notforloan    => 0,
2619                 itemlost      => 0,
2620                 withdrawn     => 0,
2621                 biblionumber  => $biblioitem->{biblionumber},
2622                 biblioitemnumber => $biblioitem->{biblioitemnumber},
2623             }
2624         }
2625     )->store;
2626
2627     my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2628     is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2629     is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2630 };
2631
2632 subtest 'CanBookBeIssued | notforloan' => sub {
2633     plan tests => 2;
2634
2635     t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
2636
2637     my $library = $builder->build( { source => 'Branch' } );
2638     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
2639
2640     my $itemtype = $builder->build(
2641         {
2642             source => 'Itemtype',
2643             value  => { notforloan => undef, }
2644         }
2645     );
2646
2647     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
2648     my $item = $builder->build_object(
2649         {
2650             class => 'Koha::Items',
2651             value  => {
2652                 homebranch    => $library->{branchcode},
2653                 holdingbranch => $library->{branchcode},
2654                 notforloan    => 0,
2655                 itemlost      => 0,
2656                 withdrawn     => 0,
2657                 itype         => $itemtype->{itemtype},
2658                 biblionumber  => $biblioitem->{biblionumber},
2659                 biblioitemnumber => $biblioitem->{biblioitemnumber},
2660             }
2661         }
2662     )->store;
2663
2664     my ( $issuingimpossible, $needsconfirmation );
2665
2666
2667     subtest 'item-level_itypes = 1' => sub {
2668         plan tests => 6;
2669
2670         t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
2671         # Is for loan at item type and item level
2672         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2673         is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2674         is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2675
2676         # not for loan at item type level
2677         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
2678         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2679         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2680         is_deeply(
2681             $issuingimpossible,
2682             { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
2683             'Item can not be issued, not for loan at item type level'
2684         );
2685
2686         # not for loan at item level
2687         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
2688         $item->notforloan( 1 )->store;
2689         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2690         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2691         is_deeply(
2692             $issuingimpossible,
2693             { NOT_FOR_LOAN => 1, item_notforloan => 1 },
2694             'Item can not be issued, not for loan at item type level'
2695         );
2696     };
2697
2698     subtest 'item-level_itypes = 0' => sub {
2699         plan tests => 6;
2700
2701         t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
2702
2703         # We set another itemtype for biblioitem
2704         my $itemtype = $builder->build(
2705             {
2706                 source => 'Itemtype',
2707                 value  => { notforloan => undef, }
2708             }
2709         );
2710
2711         # for loan at item type and item level
2712         $item->notforloan(0)->store;
2713         $item->biblioitem->itemtype($itemtype->{itemtype})->store;
2714         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2715         is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2716         is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2717
2718         # not for loan at item type level
2719         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
2720         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2721         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2722         is_deeply(
2723             $issuingimpossible,
2724             { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
2725             'Item can not be issued, not for loan at item type level'
2726         );
2727
2728         # not for loan at item level
2729         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
2730         $item->notforloan( 1 )->store;
2731         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2732         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2733         is_deeply(
2734             $issuingimpossible,
2735             { NOT_FOR_LOAN => 1, item_notforloan => 1 },
2736             'Item can not be issued, not for loan at item type level'
2737         );
2738     };
2739
2740     # TODO test with AllowNotForLoanOverride = 1
2741 };
2742
2743 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
2744     plan tests => 1;
2745
2746     t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
2747     my $item = $builder->build_object({ class => 'Koha::Items', value  => { onloan => '2018-01-01' }});
2748     AddReturn( $item->barcode, $item->homebranch );
2749     $item->discard_changes; # refresh
2750     is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
2751 };
2752
2753 $schema->storage->txn_rollback;
2754 C4::Context->clear_syspref_cache();
2755 $cache->clear_from_cache('single_holidays');
2756
2757 sub set_userenv {
2758     my ( $library ) = @_;
2759     C4::Context->set_userenv(0,0,0,'firstname','surname', $library->{branchcode}, $library->{branchname}, '', '', '');
2760 }
2761
2762 sub str {
2763     my ( $error, $question, $alert ) = @_;
2764     my $s;
2765     $s  = %$error    ? ' (error: '    . join( ' ', keys %$error    ) . ')' : '';
2766     $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
2767     $s .= %$alert    ? ' (alert: '    . join( ' ', keys %$alert    ) . ')' : '';
2768     return $s;
2769 }
2770
2771 sub add_biblio {
2772     my ($title, $author) = @_;
2773
2774     my $marcflavour = C4::Context->preference('marcflavour');
2775
2776     my $biblio = MARC::Record->new();
2777     if ($title) {
2778         my $tag = $marcflavour eq 'UNIMARC' ? '200' : '245';
2779         $biblio->append_fields(
2780             MARC::Field->new($tag, ' ', ' ', a => $title),
2781         );
2782     }
2783
2784     if ($author) {
2785         my ($tag, $code) = $marcflavour eq 'UNIMARC' ? (200, 'f') : (100, 'a');
2786         $biblio->append_fields(
2787             MARC::Field->new($tag, ' ', ' ', $code => $author),
2788         );
2789     }
2790
2791     return AddBiblio($biblio, '');
2792 }
2793
2794 sub test_debarment_on_checkout {
2795     my ($params) = @_;
2796     my $item     = $params->{item};
2797     my $library  = $params->{library};
2798     my $patron   = $params->{patron};
2799     my $due_date = $params->{due_date} || dt_from_string;
2800     my $return_date = $params->{return_date} || dt_from_string;
2801     my $expected_expiration_date = $params->{expiration_date};
2802
2803     $expected_expiration_date = output_pref(
2804         {
2805             dt         => $expected_expiration_date,
2806             dateformat => 'sql',
2807             dateonly   => 1,
2808         }
2809     );
2810     my @caller      = caller;
2811     my $line_number = $caller[2];
2812     AddIssue( $patron, $item->{barcode}, $due_date );
2813
2814     my ( undef, $message ) = AddReturn( $item->{barcode}, $library->{branchcode},
2815         undef, undef, $return_date );
2816     is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' )
2817         or diag('AddReturn returned message ' . Dumper $message );
2818     my $debarments = Koha::Patron::Debarments::GetDebarments(
2819         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2820     is( scalar(@$debarments), 1, 'Test at line ' . $line_number );
2821
2822     is( $debarments->[0]->{expiration},
2823         $expected_expiration_date, 'Test at line ' . $line_number );
2824     Koha::Patron::Debarments::DelUniqueDebarment(
2825         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2826 }