Bug 21798: Replace 2 more occurrences
[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 use utf8;
20
21 use Test::More tests => 122;
22
23 use Data::Dumper;
24 use DateTime;
25 use POSIX qw( floor );
26 use t::lib::Mocks;
27 use t::lib::TestBuilder;
28
29 use C4::Accounts;
30 use C4::Calendar;
31 use C4::Circulation;
32 use C4::Biblio;
33 use C4::Items;
34 use C4::Log;
35 use C4::Reserves;
36 use C4::Overdues qw(UpdateFine CalcFine);
37 use Koha::DateUtils;
38 use Koha::Database;
39 use Koha::IssuingRules;
40 use Koha::Checkouts;
41 use Koha::Patrons;
42 use Koha::Subscriptions;
43 use Koha::Account::Lines;
44 use Koha::Account::Offsets;
45
46 my $schema = Koha::Database->schema;
47 $schema->storage->txn_begin;
48 my $builder = t::lib::TestBuilder->new;
49 my $dbh = C4::Context->dbh;
50
51 # Start transaction
52 $dbh->{RaiseError} = 1;
53
54 my $cache = Koha::Caches->get_instance();
55 $dbh->do(q|DELETE FROM special_holidays|);
56 $dbh->do(q|DELETE FROM repeatable_holidays|);
57 $cache->clear_from_cache('single_holidays');
58
59 # Start with a clean slate
60 $dbh->do('DELETE FROM issues');
61 $dbh->do('DELETE FROM borrowers');
62
63 my $library = $builder->build({
64     source => 'Branch',
65 });
66 my $library2 = $builder->build({
67     source => 'Branch',
68 });
69 my $itemtype = $builder->build(
70     {   source => 'Itemtype',
71         value  => { notforloan => undef, rentalcharge => 0, defaultreplacecost => undef, processfee => undef }
72     }
73 )->{itemtype};
74 my $patron_category = $builder->build(
75     {
76         source => 'Category',
77         value  => {
78             category_type                 => 'P',
79             enrolmentfee                  => 0,
80             BlockExpiredPatronOpacActions => -1, # Pick the pref value
81         }
82     }
83 );
84
85 my $CircControl = C4::Context->preference('CircControl');
86 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
87
88 my $item = {
89     homebranch => $library2->{branchcode},
90     holdingbranch => $library2->{branchcode}
91 };
92
93 my $borrower = {
94     branchcode => $library2->{branchcode}
95 };
96
97 # No userenv, PickupLibrary
98 t::lib::Mocks::mock_preference('IndependentBranches', '0');
99 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
100 is(
101     C4::Context->preference('CircControl'),
102     'PickupLibrary',
103     'CircControl changed to PickupLibrary'
104 );
105 is(
106     C4::Circulation::_GetCircControlBranch($item, $borrower),
107     $item->{$HomeOrHoldingBranch},
108     '_GetCircControlBranch returned item branch (no userenv defined)'
109 );
110
111 # No userenv, PatronLibrary
112 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
113 is(
114     C4::Context->preference('CircControl'),
115     'PatronLibrary',
116     'CircControl changed to PatronLibrary'
117 );
118 is(
119     C4::Circulation::_GetCircControlBranch($item, $borrower),
120     $borrower->{branchcode},
121     '_GetCircControlBranch returned borrower branch'
122 );
123
124 # No userenv, ItemHomeLibrary
125 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
126 is(
127     C4::Context->preference('CircControl'),
128     'ItemHomeLibrary',
129     'CircControl changed to ItemHomeLibrary'
130 );
131 is(
132     $item->{$HomeOrHoldingBranch},
133     C4::Circulation::_GetCircControlBranch($item, $borrower),
134     '_GetCircControlBranch returned item branch'
135 );
136
137 # Now, set a userenv
138 t::lib::Mocks::mock_userenv({ branchcode => $library2->{branchcode} });
139 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
140
141 # Userenv set, PickupLibrary
142 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
143 is(
144     C4::Context->preference('CircControl'),
145     'PickupLibrary',
146     'CircControl changed to PickupLibrary'
147 );
148 is(
149     C4::Circulation::_GetCircControlBranch($item, $borrower),
150     $library2->{branchcode},
151     '_GetCircControlBranch returned current branch'
152 );
153
154 # Userenv set, PatronLibrary
155 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
156 is(
157     C4::Context->preference('CircControl'),
158     'PatronLibrary',
159     'CircControl changed to PatronLibrary'
160 );
161 is(
162     C4::Circulation::_GetCircControlBranch($item, $borrower),
163     $borrower->{branchcode},
164     '_GetCircControlBranch returned borrower branch'
165 );
166
167 # Userenv set, ItemHomeLibrary
168 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
169 is(
170     C4::Context->preference('CircControl'),
171     'ItemHomeLibrary',
172     'CircControl changed to ItemHomeLibrary'
173 );
174 is(
175     C4::Circulation::_GetCircControlBranch($item, $borrower),
176     $item->{$HomeOrHoldingBranch},
177     '_GetCircControlBranch returned item branch'
178 );
179
180 # Reset initial configuration
181 t::lib::Mocks::mock_preference('CircControl', $CircControl);
182 is(
183     C4::Context->preference('CircControl'),
184     $CircControl,
185     'CircControl reset to its initial value'
186 );
187
188 # Set a simple circ policy
189 $dbh->do('DELETE FROM issuingrules');
190 $dbh->do(
191     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
192                                 maxissueqty, issuelength, lengthunit,
193                                 renewalsallowed, renewalperiod,
194                                 norenewalbefore, auto_renew,
195                                 fine, chargeperiod)
196       VALUES (?, ?, ?, ?,
197               ?, ?, ?,
198               ?, ?,
199               ?, ?,
200               ?, ?
201              )
202     },
203     {},
204     '*', '*', '*', 25,
205     20, 14, 'days',
206     1, 7,
207     undef, 0,
208     .10, 1
209 );
210
211 # Test C4::Circulation::ProcessOfflinePayment
212 my $sth = C4::Context->dbh->prepare("SELECT COUNT(*) FROM accountlines WHERE amount = '-123.45' AND accounttype = 'Pay'");
213 $sth->execute();
214 my ( $original_count ) = $sth->fetchrow_array();
215
216 C4::Context->dbh->do("INSERT INTO borrowers ( cardnumber, surname, firstname, categorycode, branchcode ) VALUES ( '99999999999', 'Hall', 'Kyle', ?, ? )", undef, $patron_category->{categorycode}, $library2->{branchcode} );
217
218 C4::Circulation::ProcessOfflinePayment({ cardnumber => '99999999999', amount => '123.45' });
219
220 $sth->execute();
221 my ( $new_count ) = $sth->fetchrow_array();
222
223 ok( $new_count == $original_count  + 1, 'ProcessOfflinePayment makes payment correctly' );
224
225 C4::Context->dbh->do("DELETE FROM accountlines WHERE borrowernumber IN ( SELECT borrowernumber FROM borrowers WHERE cardnumber = '99999999999' )");
226 C4::Context->dbh->do("DELETE FROM borrowers WHERE cardnumber = '99999999999'");
227 C4::Context->dbh->do("DELETE FROM accountlines");
228 {
229 # CanBookBeRenewed tests
230     C4::Context->set_preference('ItemsDeniedRenewal','');
231     # Generate test biblio
232     my $biblio = $builder->gimme_a_biblio();
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         $biblio->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         $biblio->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         $biblio->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, $biblio->biblionumber,
347         $bibitems,  $priority, $resdate, $expdate, $notes,
348         'a 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   => $biblio->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   => $biblio->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 => $biblio->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, $biblio->biblionumber,
412         $bibitems,  $priority, $resdate, $expdate, $notes,
413         'a 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 }, $biblio->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 }, $biblio->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         $biblio->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         $biblio->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         $biblio->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 => $biblio->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         $biblio->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  => $biblio->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 => $biblio->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 => $biblio->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  => $biblio->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     $line = Koha::Account::Lines->find($line->id);
858     is( $line->accounttype, 'F', 'Account type correctly changed from FU to F' );
859
860     my $item = Koha::Database->new()->schema()->resultset('Item')->find($itemnumber);
861     ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
862     my $checkout = Koha::Checkouts->find({ itemnumber => $itemnumber });
863     is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
864
865     my $total_due = $dbh->selectrow_array(
866         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
867         undef, $renewing_borrower->{borrowernumber}
868     );
869
870     is( $total_due, '15.000000', 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
871
872     C4::Context->dbh->do("DELETE FROM accountlines");
873
874     C4::Overdues::UpdateFine(
875         {
876             issue_id       => $issue2->id(),
877             itemnumber     => $itemnumber2,
878             borrowernumber => $renewing_borrower->{borrowernumber},
879             amount         => 15.00,
880             type           => q{},
881             due            => Koha::DateUtils::output_pref($datedue)
882         }
883     );
884
885     LostItem( $itemnumber2, 'test', 0 );
886
887     my $item2 = Koha::Database->new()->schema()->resultset('Item')->find($itemnumber2);
888     ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
889     ok( Koha::Checkouts->find({ itemnumber => $itemnumber2 }), 'LostItem called without forced return has checked in the item' );
890
891     $total_due = $dbh->selectrow_array(
892         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
893         undef, $renewing_borrower->{borrowernumber}
894     );
895
896     ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
897
898     my $future = dt_from_string();
899     $future->add( days => 7 );
900     my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
901     ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
902
903     # Users cannot renew any item if there is an overdue item
904     t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
905     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber6);
906     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
907     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber7);
908     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
909
910     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
911     $checkout = Koha::Checkouts->find( { itemnumber => $itemnumber3 } );
912     LostItem( $itemnumber3, 'test', 0 );
913     my $accountline = Koha::Account::Lines->find( { itemnumber => $itemnumber3 } );
914     is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
915
916   }
917
918 {
919     # GetUpcomingDueIssues tests
920     my $barcode  = 'R00000342';
921     my $barcode2 = 'R00000343';
922     my $barcode3 = 'R00000344';
923     my $branch   = $library2->{branchcode};
924
925     #Create another record
926     my $biblio2 = $builder->gimme_a_biblio();
927
928     #Create third item
929     AddItem(
930         {
931             homebranch       => $branch,
932             holdingbranch    => $branch,
933             barcode          => $barcode3,
934             itype            => $itemtype
935         },
936         $biblio2->biblionumber
937     );
938
939     # Create a borrower
940     my %a_borrower_data = (
941         firstname =>  'Fridolyn',
942         surname => 'SOMERS',
943         categorycode => $patron_category->{categorycode},
944         branchcode => $branch,
945     );
946
947     my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
948     my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
949
950     my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
951     my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
952     my $today = DateTime->today(time_zone => C4::Context->tz());
953
954     my $issue = AddIssue( $a_borrower, $barcode, $yesterday );
955     my $datedue = dt_from_string( $issue->date_due() );
956     my $issue2 = AddIssue( $a_borrower, $barcode2, $two_days_ahead );
957     my $datedue2 = dt_from_string( $issue->date_due() );
958
959     my $upcoming_dues;
960
961     # GetUpcomingDueIssues tests
962     for my $i(0..1) {
963         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
964         is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
965     }
966
967     #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
968     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
969     is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
970
971     for my $i(3..5) {
972         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
973         is ( scalar( @$upcoming_dues ), 1,
974             "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
975     }
976
977     # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
978
979     my $issue3 = AddIssue( $a_borrower, $barcode3, $today );
980
981     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
982     is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
983
984     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
985     is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
986
987     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
988     is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
989
990     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 }  );
991     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
992
993     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
994     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
995
996     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
997     is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
998
999 }
1000
1001 {
1002     my $barcode  = '1234567890';
1003     my $branch   = $library2->{branchcode};
1004
1005     my $biblio = $builder->gimme_a_biblio();
1006
1007     #Create third item
1008     my ( undef, undef, $itemnumber ) = AddItem(
1009         {
1010             homebranch       => $branch,
1011             holdingbranch    => $branch,
1012             barcode          => $barcode,
1013             itype            => $itemtype
1014         },
1015         $biblio->biblionumber
1016     );
1017
1018     # Create a borrower
1019     my %a_borrower_data = (
1020         firstname =>  'Kyle',
1021         surname => 'Hall',
1022         categorycode => $patron_category->{categorycode},
1023         branchcode => $branch,
1024     );
1025
1026     my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1027
1028     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1029     my $issue = AddIssue( $borrower, $barcode );
1030     UpdateFine(
1031         {
1032             issue_id       => $issue->id(),
1033             itemnumber     => $itemnumber,
1034             borrowernumber => $borrowernumber,
1035             amount         => 0,
1036             type           => q{}
1037         }
1038     );
1039
1040     my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $itemnumber );
1041     my $count = $hr->{count};
1042
1043     is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1044 }
1045
1046 {
1047     $dbh->do('DELETE FROM issues');
1048     $dbh->do('DELETE FROM items');
1049     $dbh->do('DELETE FROM issuingrules');
1050     $dbh->do(
1051         q{
1052         INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, maxissueqty, issuelength, lengthunit, renewalsallowed, renewalperiod,
1053                     norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
1054         },
1055         {},
1056         '*', '*', '*', 25,
1057         20,  14,  'days',
1058         1,   7,
1059         undef,  0,
1060         .10, 1
1061     );
1062     my $biblio = $builder->gimme_a_biblio();
1063
1064     my $barcode1 = '1234';
1065     my ( undef, undef, $itemnumber1 ) = AddItem(
1066         {
1067             homebranch    => $library2->{branchcode},
1068             holdingbranch => $library2->{branchcode},
1069             barcode       => $barcode1,
1070             itype         => $itemtype
1071         },
1072         $biblio->biblionumber
1073     );
1074     my $barcode2 = '4321';
1075     my ( undef, undef, $itemnumber2 ) = AddItem(
1076         {
1077             homebranch    => $library2->{branchcode},
1078             holdingbranch => $library2->{branchcode},
1079             barcode       => $barcode2,
1080             itype         => $itemtype
1081         },
1082         $biblio->biblionumber
1083     );
1084
1085     my $borrowernumber1 = Koha::Patron->new({
1086         firstname    => 'Kyle',
1087         surname      => 'Hall',
1088         categorycode => $patron_category->{categorycode},
1089         branchcode   => $library2->{branchcode},
1090     })->store->borrowernumber;
1091     my $borrowernumber2 = Koha::Patron->new({
1092         firstname    => 'Chelsea',
1093         surname      => 'Hall',
1094         categorycode => $patron_category->{categorycode},
1095         branchcode   => $library2->{branchcode},
1096     })->store->borrowernumber;
1097
1098     my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1099     my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1100
1101     my $issue = AddIssue( $borrower1, $barcode1 );
1102
1103     my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1104     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1105
1106     AddReserve(
1107         $library2->{branchcode}, $borrowernumber2, $biblio->biblionumber,
1108         '',  1, undef, undef, '',
1109         undef, undef, undef
1110     );
1111
1112     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1113     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1114     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1115     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1116
1117     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1118     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1119     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1120     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1121
1122     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1123     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1124     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1125     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1126
1127     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1128     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1129     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1130     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1131
1132     # Setting item not checked out to be not for loan but holdable
1133     ModItem({ notforloan => -1 }, $biblio->biblionumber, $itemnumber2);
1134
1135     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
1136     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' );
1137 }
1138
1139 {
1140     # Don't allow renewing onsite checkout
1141     my $barcode  = 'R00000XXX';
1142     my $branch   = $library->{branchcode};
1143
1144     #Create another record
1145     my $biblio = $builder->gimme_a_biblio();
1146
1147     my (undef, undef, $itemnumber) = AddItem(
1148         {
1149             homebranch       => $branch,
1150             holdingbranch    => $branch,
1151             barcode          => $barcode,
1152             itype            => $itemtype
1153         },
1154         $biblio->biblionumber
1155     );
1156
1157     my $borrowernumber = Koha::Patron->new({
1158         firstname =>  'fn',
1159         surname => 'dn',
1160         categorycode => $patron_category->{categorycode},
1161         branchcode => $branch,
1162     })->store->borrowernumber;
1163
1164     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1165
1166     my $issue = AddIssue( $borrower, $barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1167     my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $itemnumber );
1168     is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1169     is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1170 }
1171
1172 {
1173     my $library = $builder->build({ source => 'Branch' });
1174
1175     my $biblio = $builder->gimme_a_biblio();
1176
1177     my $barcode = 'just a barcode';
1178     my ( undef, undef, $itemnumber ) = AddItem(
1179         {
1180             homebranch       => $library->{branchcode},
1181             holdingbranch    => $library->{branchcode},
1182             barcode          => $barcode,
1183             itype            => $itemtype
1184         },
1185         $biblio->biblionumber,
1186     );
1187
1188     my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1189
1190     my $issue = AddIssue( $patron, $barcode );
1191     UpdateFine(
1192         {
1193             issue_id       => $issue->id(),
1194             itemnumber     => $itemnumber,
1195             borrowernumber => $patron->{borrowernumber},
1196             amount         => 1,
1197             type           => q{}
1198         }
1199     );
1200     UpdateFine(
1201         {
1202             issue_id       => $issue->id(),
1203             itemnumber     => $itemnumber,
1204             borrowernumber => $patron->{borrowernumber},
1205             amount         => 2,
1206             type           => q{}
1207         }
1208     );
1209     is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1210 }
1211
1212 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1213     plan tests => 24;
1214
1215     my $homebranch    = $builder->build( { source => 'Branch' } );
1216     my $holdingbranch = $builder->build( { source => 'Branch' } );
1217     my $otherbranch   = $builder->build( { source => 'Branch' } );
1218     my $patron_1      = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1219     my $patron_2      = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1220
1221     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1222     my $item = $builder->build(
1223         {   source => 'Item',
1224             value  => {
1225                 homebranch    => $homebranch->{branchcode},
1226                 holdingbranch => $holdingbranch->{branchcode},
1227                 biblionumber  => $biblioitem->{biblionumber}
1228             }
1229         }
1230     );
1231
1232     set_userenv($holdingbranch);
1233
1234     my $issue = AddIssue( $patron_1->unblessed, $item->{barcode} );
1235     is( ref($issue), 'Koha::Schema::Result::Issue' );    # FIXME Should be Koha::Checkout
1236
1237     my ( $error, $question, $alerts );
1238
1239     # AllowReturnToBranch == anywhere
1240     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1241     ## Test that unknown barcodes don't generate internal server errors
1242     set_userenv($homebranch);
1243     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1244     ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1245     ## Can be issued from homebranch
1246     set_userenv($homebranch);
1247     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1248     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1249     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1250     ## Can be issued from holdingbranch
1251     set_userenv($holdingbranch);
1252     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1253     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1254     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1255     ## Can be issued from another branch
1256     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1257     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1258     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1259
1260     # AllowReturnToBranch == holdingbranch
1261     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1262     ## Cannot be issued from homebranch
1263     set_userenv($homebranch);
1264     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1265     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1266     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1267     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
1268     ## Can be issued from holdinbranch
1269     set_userenv($holdingbranch);
1270     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1271     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1272     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1273     ## Cannot be issued from another branch
1274     set_userenv($otherbranch);
1275     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1276     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1277     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1278     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
1279
1280     # AllowReturnToBranch == homebranch
1281     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1282     ## Can be issued from holdinbranch
1283     set_userenv($homebranch);
1284     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1285     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1286     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1287     ## Cannot be issued from holdinbranch
1288     set_userenv($holdingbranch);
1289     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1290     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1291     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1292     is( $error->{branch_to_return},         $homebranch->{branchcode} );
1293     ## Cannot be issued from holdinbranch
1294     set_userenv($otherbranch);
1295     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1296     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1297     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1298     is( $error->{branch_to_return},         $homebranch->{branchcode} );
1299
1300     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1301 };
1302
1303 subtest 'AddIssue & AllowReturnToBranch' => sub {
1304     plan tests => 9;
1305
1306     my $homebranch    = $builder->build( { source => 'Branch' } );
1307     my $holdingbranch = $builder->build( { source => 'Branch' } );
1308     my $otherbranch   = $builder->build( { source => 'Branch' } );
1309     my $patron_1      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1310     my $patron_2      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1311
1312     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1313     my $item = $builder->build(
1314         {   source => 'Item',
1315             value  => {
1316                 homebranch    => $homebranch->{branchcode},
1317                 holdingbranch => $holdingbranch->{branchcode},
1318                 notforloan    => 0,
1319                 itemlost      => 0,
1320                 withdrawn     => 0,
1321                 biblionumber  => $biblioitem->{biblionumber}
1322             }
1323         }
1324     );
1325
1326     set_userenv($holdingbranch);
1327
1328     my $ref_issue = 'Koha::Schema::Result::Issue'; # FIXME Should be Koha::Checkout
1329     my $issue = AddIssue( $patron_1, $item->{barcode} );
1330
1331     my ( $error, $question, $alerts );
1332
1333     # AllowReturnToBranch == homebranch
1334     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1335     ## Can be issued from homebranch
1336     set_userenv($homebranch);
1337     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1338     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1339     ## Can be issued from holdinbranch
1340     set_userenv($holdingbranch);
1341     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1342     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1343     ## Can be issued from another branch
1344     set_userenv($otherbranch);
1345     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1346     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1347
1348     # AllowReturnToBranch == holdinbranch
1349     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1350     ## Cannot be issued from homebranch
1351     set_userenv($homebranch);
1352     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1353     ## Can be issued from holdingbranch
1354     set_userenv($holdingbranch);
1355     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1356     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1357     ## Cannot be issued from another branch
1358     set_userenv($otherbranch);
1359     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1360
1361     # AllowReturnToBranch == homebranch
1362     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1363     ## Can be issued from homebranch
1364     set_userenv($homebranch);
1365     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1366     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1367     ## Cannot be issued from holdinbranch
1368     set_userenv($holdingbranch);
1369     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1370     ## Cannot be issued from another branch
1371     set_userenv($otherbranch);
1372     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1373     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1374 };
1375
1376 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1377     plan tests => 8;
1378
1379     my $library = $builder->build( { source => 'Branch' } );
1380     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1381
1382     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1383     my $item_1 = $builder->build(
1384         {   source => 'Item',
1385             value  => {
1386                 homebranch    => $library->{branchcode},
1387                 holdingbranch => $library->{branchcode},
1388                 biblionumber  => $biblioitem_1->{biblionumber}
1389             }
1390         }
1391     );
1392     my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1393     my $item_2 = $builder->build(
1394         {   source => 'Item',
1395             value  => {
1396                 homebranch    => $library->{branchcode},
1397                 holdingbranch => $library->{branchcode},
1398                 biblionumber  => $biblioitem_2->{biblionumber}
1399             }
1400         }
1401     );
1402
1403     my ( $error, $question, $alerts );
1404
1405     # Patron cannot issue item_1, they have overdues
1406     my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1407     my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, $yesterday );    # Add an overdue
1408
1409     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1410     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1411     is( keys(%$error) + keys(%$alerts),  0, 'No key for error and alert' . str($error, $question, $alerts) );
1412     is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
1413
1414     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1415     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1416     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1417     is( $error->{USERBLOCKEDOVERDUE},      1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
1418
1419     # Patron cannot issue item_1, they are debarred
1420     my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1421     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
1422     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1423     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1424     is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
1425
1426     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
1427     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1428     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1429     is( $error->{USERBLOCKEDNOENDDATE},    '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
1430 };
1431
1432 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
1433     plan tests => 1;
1434
1435     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1436     my $patron_category_x = $builder->build_object(
1437         {
1438             class => 'Koha::Patron::Categories',
1439             value => { category_type => 'X' }
1440         }
1441     );
1442     my $patron = $builder->build_object(
1443         {
1444             class => 'Koha::Patrons',
1445             value => {
1446                 categorycode  => $patron_category_x->categorycode,
1447                 gonenoaddress => undef,
1448                 lost          => undef,
1449                 debarred      => undef,
1450                 borrowernotes => ""
1451             }
1452         }
1453     );
1454     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1455     my $item_1 = $builder->build(
1456         {
1457             source => 'Item',
1458             value  => {
1459                 homebranch    => $library->branchcode,
1460                 holdingbranch => $library->branchcode,
1461                 biblionumber  => $biblioitem_1->{biblionumber}
1462             }
1463         }
1464     );
1465
1466     my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->{barcode} );
1467     is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
1468
1469     # TODO There are other tests to provide here
1470 };
1471
1472 subtest 'MultipleReserves' => sub {
1473     plan tests => 3;
1474
1475     my $biblio = $builder->gimme_a_biblio();
1476
1477     my $branch = $library2->{branchcode};
1478
1479     my $barcode1 = 'R00110001';
1480     my ( $item_bibnum1, $item_bibitemnum1, $itemnumber1 ) = AddItem(
1481         {
1482             homebranch       => $branch,
1483             holdingbranch    => $branch,
1484             barcode          => $barcode1,
1485             replacementprice => 12.00,
1486             itype            => $itemtype
1487         },
1488         $biblio->biblionumber
1489     );
1490
1491     my $barcode2 = 'R00110002';
1492     my ( $item_bibnum2, $item_bibitemnum2, $itemnumber2 ) = AddItem(
1493         {
1494             homebranch       => $branch,
1495             holdingbranch    => $branch,
1496             barcode          => $barcode2,
1497             replacementprice => 12.00,
1498             itype            => $itemtype
1499         },
1500         $biblio->biblionumber
1501     );
1502
1503     my $bibitems       = '';
1504     my $priority       = '1';
1505     my $resdate        = undef;
1506     my $expdate        = undef;
1507     my $notes          = '';
1508     my $checkitem      = undef;
1509     my $found          = undef;
1510
1511     my %renewing_borrower_data = (
1512         firstname =>  'John',
1513         surname => 'Renewal',
1514         categorycode => $patron_category->{categorycode},
1515         branchcode => $branch,
1516     );
1517     my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
1518     my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
1519     my $issue = AddIssue( $renewing_borrower, $barcode1);
1520     my $datedue = dt_from_string( $issue->date_due() );
1521     is (defined $issue->date_due(), 1, "item 1 checked out");
1522     my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $itemnumber1 })->borrowernumber;
1523
1524     my %reserving_borrower_data1 = (
1525         firstname =>  'Katrin',
1526         surname => 'Reservation',
1527         categorycode => $patron_category->{categorycode},
1528         branchcode => $branch,
1529     );
1530     my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
1531     AddReserve(
1532         $branch, $reserving_borrowernumber1, $biblio->biblionumber,
1533         $bibitems,  $priority, $resdate, $expdate, $notes,
1534         'a title', $checkitem, $found
1535     );
1536
1537     my %reserving_borrower_data2 = (
1538         firstname =>  'Kirk',
1539         surname => 'Reservation',
1540         categorycode => $patron_category->{categorycode},
1541         branchcode => $branch,
1542     );
1543     my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
1544     AddReserve(
1545         $branch, $reserving_borrowernumber2, $biblio->biblionumber,
1546         $bibitems,  $priority, $resdate, $expdate, $notes,
1547         'a title', $checkitem, $found
1548     );
1549
1550     {
1551         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber1, 1);
1552         is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
1553     }
1554
1555     my $barcode3 = 'R00110003';
1556     my ( $item_bibnum3, $item_bibitemnum3, $itemnumber3 ) = AddItem(
1557         {
1558             homebranch       => $branch,
1559             holdingbranch    => $branch,
1560             barcode          => $barcode3,
1561             replacementprice => 12.00,
1562             itype            => $itemtype
1563         },
1564         $biblio->biblionumber
1565     );
1566
1567     {
1568         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber1, 1);
1569         is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
1570     }
1571 };
1572
1573 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
1574     plan tests => 5;
1575
1576     my $library = $builder->build( { source => 'Branch' } );
1577     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1578
1579     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1580     my $biblionumber = $biblioitem->{biblionumber};
1581     my $item_1 = $builder->build(
1582         {   source => 'Item',
1583             value  => {
1584                 homebranch    => $library->{branchcode},
1585                 holdingbranch => $library->{branchcode},
1586                 biblionumber  => $biblionumber,
1587             }
1588         }
1589     );
1590     my $item_2 = $builder->build(
1591         {   source => 'Item',
1592             value  => {
1593                 homebranch    => $library->{branchcode},
1594                 holdingbranch => $library->{branchcode},
1595                 biblionumber  => $biblionumber,
1596             }
1597         }
1598     );
1599
1600     my ( $error, $question, $alerts );
1601     my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, dt_from_string->add( days => 1 ) );
1602
1603     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1604     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1605     is( keys(%$error) + keys(%$alerts),  0, 'No error or alert should be raised' . str($error, $question, $alerts) );
1606     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) );
1607
1608     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1609     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1610     is( keys(%$error) + keys(%$question) + keys(%$alerts),  0, 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1' . str($error, $question, $alerts) );
1611
1612     # Add a subscription
1613     Koha::Subscription->new({ biblionumber => $biblionumber })->store;
1614
1615     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1616     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1617     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) );
1618
1619     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1620     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1621     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) );
1622 };
1623
1624 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
1625     plan tests => 8;
1626
1627     my $library = $builder->build( { source => 'Branch' } );
1628     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1629
1630     # Add 2 items
1631     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1632     my $item_1 = $builder->build(
1633         {
1634             source => 'Item',
1635             value  => {
1636                 homebranch    => $library->{branchcode},
1637                 holdingbranch => $library->{branchcode},
1638                 notforloan    => 0,
1639                 itemlost      => 0,
1640                 withdrawn     => 0,
1641                 biblionumber  => $biblioitem_1->{biblionumber}
1642             }
1643         }
1644     );
1645     my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1646     my $item_2 = $builder->build(
1647         {
1648             source => 'Item',
1649             value  => {
1650                 homebranch    => $library->{branchcode},
1651                 holdingbranch => $library->{branchcode},
1652                 notforloan    => 0,
1653                 itemlost      => 0,
1654                 withdrawn     => 0,
1655                 biblionumber  => $biblioitem_2->{biblionumber}
1656             }
1657         }
1658     );
1659
1660     # And the issuing rule
1661     Koha::IssuingRules->search->delete;
1662     my $rule = Koha::IssuingRule->new(
1663         {
1664             categorycode => '*',
1665             itemtype     => '*',
1666             branchcode   => '*',
1667             maxissueqty  => 99,
1668             issuelength  => 1,
1669             firstremind  => 1,        # 1 day of grace
1670             finedays     => 2,        # 2 days of fine per day of overdue
1671             lengthunit   => 'days',
1672         }
1673     );
1674     $rule->store();
1675
1676     # Patron cannot issue item_1, they have overdues
1677     my $five_days_ago = dt_from_string->subtract( days => 5 );
1678     my $ten_days_ago  = dt_from_string->subtract( days => 10 );
1679     AddIssue( $patron, $item_1->{barcode}, $five_days_ago );    # Add an overdue
1680     AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1681       ;    # Add another overdue
1682
1683     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
1684     AddReturn( $item_1->{barcode}, $library->{branchcode},
1685         undef, undef, dt_from_string );
1686     my $debarments = Koha::Patron::Debarments::GetDebarments(
1687         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1688     is( scalar(@$debarments), 1 );
1689
1690     # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
1691     # Same for the others
1692     my $expected_expiration = output_pref(
1693         {
1694             dt         => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1695             dateformat => 'sql',
1696             dateonly   => 1
1697         }
1698     );
1699     is( $debarments->[0]->{expiration}, $expected_expiration );
1700
1701     AddReturn( $item_2->{barcode}, $library->{branchcode},
1702         undef, undef, dt_from_string );
1703     $debarments = Koha::Patron::Debarments::GetDebarments(
1704         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1705     is( scalar(@$debarments), 1 );
1706     $expected_expiration = output_pref(
1707         {
1708             dt         => dt_from_string->add( days => ( 10 - 1 ) * 2 ),
1709             dateformat => 'sql',
1710             dateonly   => 1
1711         }
1712     );
1713     is( $debarments->[0]->{expiration}, $expected_expiration );
1714
1715     Koha::Patron::Debarments::DelUniqueDebarment(
1716         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1717
1718     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
1719     AddIssue( $patron, $item_1->{barcode}, $five_days_ago );    # Add an overdue
1720     AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1721       ;    # Add another overdue
1722     AddReturn( $item_1->{barcode}, $library->{branchcode},
1723         undef, undef, dt_from_string );
1724     $debarments = Koha::Patron::Debarments::GetDebarments(
1725         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1726     is( scalar(@$debarments), 1 );
1727     $expected_expiration = output_pref(
1728         {
1729             dt         => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1730             dateformat => 'sql',
1731             dateonly   => 1
1732         }
1733     );
1734     is( $debarments->[0]->{expiration}, $expected_expiration );
1735
1736     AddReturn( $item_2->{barcode}, $library->{branchcode},
1737         undef, undef, dt_from_string );
1738     $debarments = Koha::Patron::Debarments::GetDebarments(
1739         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1740     is( scalar(@$debarments), 1 );
1741     $expected_expiration = output_pref(
1742         {
1743             dt => dt_from_string->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
1744             dateformat => 'sql',
1745             dateonly   => 1
1746         }
1747     );
1748     is( $debarments->[0]->{expiration}, $expected_expiration );
1749 };
1750
1751 subtest 'AddReturn + suspension_chargeperiod' => sub {
1752     plan tests => 21;
1753
1754     my $library = $builder->build( { source => 'Branch' } );
1755     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1756
1757     # Add 2 items
1758     my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1759     my $item_1 = $builder->build(
1760         {
1761             source => 'Item',
1762             value  => {
1763                 homebranch    => $library->{branchcode},
1764                 holdingbranch => $library->{branchcode},
1765                 notforloan    => 0,
1766                 itemlost      => 0,
1767                 withdrawn     => 0,
1768                 biblionumber  => $biblioitem_1->{biblionumber}
1769             }
1770         }
1771     );
1772
1773     # And the issuing rule
1774     Koha::IssuingRules->search->delete;
1775     my $rule = Koha::IssuingRule->new(
1776         {
1777             categorycode => '*',
1778             itemtype     => '*',
1779             branchcode   => '*',
1780             maxissueqty  => 99,
1781             issuelength  => 1,
1782             firstremind  => 0,        # 0 day of grace
1783             finedays     => 2,        # 2 days of fine per day of overdue
1784             suspension_chargeperiod => 1,
1785             lengthunit   => 'days',
1786         }
1787     );
1788     $rule->store();
1789
1790     my $five_days_ago = dt_from_string->subtract( days => 5 );
1791     # We want to charge 2 days every day, without grace
1792     # With 5 days of overdue: 5 * Z
1793     my $expected_expiration = dt_from_string->add( days => ( 5 * 2 ) / 1 );
1794     test_debarment_on_checkout(
1795         {
1796             item            => $item_1,
1797             library         => $library,
1798             patron          => $patron,
1799             due_date        => $five_days_ago,
1800             expiration_date => $expected_expiration,
1801         }
1802     );
1803
1804     # We want to charge 2 days every 2 days, without grace
1805     # With 5 days of overdue: (5 * 2) / 2
1806     $rule->suspension_chargeperiod(2)->store;
1807     $expected_expiration = dt_from_string->add( days => floor( 5 * 2 ) / 2 );
1808     test_debarment_on_checkout(
1809         {
1810             item            => $item_1,
1811             library         => $library,
1812             patron          => $patron,
1813             due_date        => $five_days_ago,
1814             expiration_date => $expected_expiration,
1815         }
1816     );
1817
1818     # We want to charge 2 days every 3 days, with 1 day of grace
1819     # With 5 days of overdue: ((5-1) / 3 ) * 2
1820     $rule->suspension_chargeperiod(3)->store;
1821     $rule->firstremind(1)->store;
1822     $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
1823     test_debarment_on_checkout(
1824         {
1825             item            => $item_1,
1826             library         => $library,
1827             patron          => $patron,
1828             due_date        => $five_days_ago,
1829             expiration_date => $expected_expiration,
1830         }
1831     );
1832
1833     # Use finesCalendar to know if holiday must be skipped to calculate the due date
1834     # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
1835     $rule->finedays(2)->store;
1836     $rule->suspension_chargeperiod(1)->store;
1837     $rule->firstremind(0)->store;
1838     t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
1839
1840     # Adding a holiday 2 days ago
1841     my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
1842     my $two_days_ago = dt_from_string->subtract( days => 2 );
1843     $calendar->insert_single_holiday(
1844         day             => $two_days_ago->day,
1845         month           => $two_days_ago->month,
1846         year            => $two_days_ago->year,
1847         title           => 'holidayTest-2d',
1848         description     => 'holidayDesc 2 days ago'
1849     );
1850     # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
1851     $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
1852     test_debarment_on_checkout(
1853         {
1854             item            => $item_1,
1855             library         => $library,
1856             patron          => $patron,
1857             due_date        => $five_days_ago,
1858             expiration_date => $expected_expiration,
1859         }
1860     );
1861
1862     # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
1863     my $two_days_ahead = dt_from_string->add( days => 2 );
1864     $calendar->insert_single_holiday(
1865         day             => $two_days_ahead->day,
1866         month           => $two_days_ahead->month,
1867         year            => $two_days_ahead->year,
1868         title           => 'holidayTest+2d',
1869         description     => 'holidayDesc 2 days ahead'
1870     );
1871
1872     # Same as above, but we should skip D+2
1873     $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
1874     test_debarment_on_checkout(
1875         {
1876             item            => $item_1,
1877             library         => $library,
1878             patron          => $patron,
1879             due_date        => $five_days_ago,
1880             expiration_date => $expected_expiration,
1881         }
1882     );
1883
1884     # Adding another holiday, day of expiration date
1885     my $expected_expiration_dt = dt_from_string($expected_expiration);
1886     $calendar->insert_single_holiday(
1887         day             => $expected_expiration_dt->day,
1888         month           => $expected_expiration_dt->month,
1889         year            => $expected_expiration_dt->year,
1890         title           => 'holidayTest_exp',
1891         description     => 'holidayDesc on expiration date'
1892     );
1893     # Expiration date will be the day after
1894     test_debarment_on_checkout(
1895         {
1896             item            => $item_1,
1897             library         => $library,
1898             patron          => $patron,
1899             due_date        => $five_days_ago,
1900             expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
1901         }
1902     );
1903
1904     test_debarment_on_checkout(
1905         {
1906             item            => $item_1,
1907             library         => $library,
1908             patron          => $patron,
1909             return_date     => dt_from_string->add(days => 5),
1910             expiration_date => dt_from_string->add(days => 5 + (5 * 2 - 1) ),
1911         }
1912     );
1913 };
1914
1915 subtest 'AddReturn | is_overdue' => sub {
1916     plan tests => 5;
1917
1918     t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
1919     t::lib::Mocks::mock_preference('finesMode', 'production');
1920     t::lib::Mocks::mock_preference('MaxFine', '100');
1921
1922     my $library = $builder->build( { source => 'Branch' } );
1923     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1924
1925     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1926     my $item = $builder->build(
1927         {
1928             source => 'Item',
1929             value  => {
1930                 homebranch    => $library->{branchcode},
1931                 holdingbranch => $library->{branchcode},
1932                 notforloan    => 0,
1933                 itemlost      => 0,
1934                 withdrawn     => 0,
1935                 biblionumber  => $biblioitem->{biblionumber},
1936             }
1937         }
1938     );
1939
1940     Koha::IssuingRules->search->delete;
1941     my $rule = Koha::IssuingRule->new(
1942         {
1943             categorycode => '*',
1944             itemtype     => '*',
1945             branchcode   => '*',
1946             maxissueqty  => 99,
1947             issuelength  => 6,
1948             lengthunit   => 'days',
1949             fine         => 1, # Charge 1 every day of overdue
1950             chargeperiod => 1,
1951         }
1952     );
1953     $rule->store();
1954
1955     my $one_day_ago   = dt_from_string->subtract( days => 1 );
1956     my $five_days_ago = dt_from_string->subtract( days => 5 );
1957     my $ten_days_ago  = dt_from_string->subtract( days => 10 );
1958     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1959
1960     # No date specify, today will be used
1961     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1962     AddReturn( $item->{barcode}, $library->{branchcode} );
1963     is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
1964     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1965
1966     # specify return date 5 days before => no overdue
1967     AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
1968     AddReturn( $item->{barcode}, $library->{branchcode}, undef, undef, $ten_days_ago );
1969     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
1970     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1971
1972     # specify return date 5 days later => overdue
1973     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1974     AddReturn( $item->{barcode}, $library->{branchcode}, undef, undef, $five_days_ago );
1975     is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
1976     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1977
1978     # specify dropbox date 5 days before => no overdue
1979     AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
1980     AddReturn( $item->{barcode}, $library->{branchcode}, undef, 1, undef, $ten_days_ago );
1981     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
1982     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1983
1984     # specify dropbox date 5 days later => overdue, or... not
1985     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1986     AddReturn( $item->{barcode}, $library->{branchcode}, undef, 1, undef, $five_days_ago );
1987     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
1988     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1989 };
1990
1991 subtest '_FixAccountForLostAndReturned' => sub {
1992
1993     plan tests => 5;
1994
1995     t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
1996     t::lib::Mocks::mock_preference( 'WhenLostForgiveFine',          0 );
1997
1998     my $processfee_amount  = 20;
1999     my $replacement_amount = 99.00;
2000     my $item_type          = $builder->build_object(
2001         {   class => 'Koha::ItemTypes',
2002             value => {
2003                 notforloan         => undef,
2004                 rentalcharge       => 0,
2005                 defaultreplacecost => undef,
2006                 processfee         => $processfee_amount
2007             }
2008         }
2009     );
2010     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2011
2012     my $biblio = $builder->gimme_a_biblio({ author => 'Hall, Daria' });
2013
2014     subtest 'Full write-off tests' => sub {
2015
2016         plan tests => 10;
2017
2018         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2019         my $barcode = 'KD123456789';
2020
2021         my ( undef, undef, $item_id ) = AddItem(
2022             {   homebranch       => $library->branchcode,
2023                 holdingbranch    => $library->branchcode,
2024                 barcode          => $barcode,
2025                 replacementprice => $replacement_amount,
2026                 itype            => $item_type->itemtype
2027             },
2028             $biblio->biblionumber
2029         );
2030
2031         AddIssue( $patron->unblessed, $barcode );
2032
2033         # Simulate item marked as lost
2034         ModItem( { itemlost => 3 }, $biblio->biblionumber, $item_id );
2035         LostItem( $item_id, 1 );
2036
2037         my $processing_fee_lines = Koha::Account::Lines->search(
2038             { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'PF' } );
2039         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2040         my $processing_fee_line = $processing_fee_lines->next;
2041         is( $processing_fee_line->amount + 0,
2042             $processfee_amount, 'The right PF amount is generated' );
2043         is( $processing_fee_line->amountoutstanding + 0,
2044             $processfee_amount, 'The right PF amountoutstanding is generated' );
2045
2046         my $lost_fee_lines = Koha::Account::Lines->search(
2047             { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'L' } );
2048         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2049         my $lost_fee_line = $lost_fee_lines->next;
2050         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2051         is( $lost_fee_line->amountoutstanding + 0,
2052             $replacement_amount, 'The right L amountoutstanding is generated' );
2053
2054         my $account = $patron->account;
2055         my $debts   = $account->outstanding_debits;
2056
2057         # Write off the debt
2058         my $credit = $account->add_credit(
2059             {   amount => $account->balance,
2060                 type   => 'writeoff'
2061             }
2062         );
2063         $credit->apply( { debits => $debts, offset_type => 'Writeoff' } );
2064
2065         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item_id, $patron->id );
2066         is( $credit_return_id, undef, 'No CR account line added' );
2067
2068         $lost_fee_line->discard_changes; # reload from DB
2069         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2070         is( $lost_fee_line->accounttype,
2071             'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2072
2073         is( $patron->account->balance, -0, 'The patron balance is 0, everything was written off' );
2074     };
2075
2076     subtest 'Full payment tests' => sub {
2077
2078         plan tests => 12;
2079
2080         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2081         my $barcode = 'KD123456790';
2082
2083         my ( undef, undef, $item_id ) = AddItem(
2084             {   homebranch       => $library->branchcode,
2085                 holdingbranch    => $library->branchcode,
2086                 barcode          => $barcode,
2087                 replacementprice => $replacement_amount,
2088                 itype            => $item_type->itemtype
2089             },
2090             $biblio->biblionumber
2091         );
2092
2093         AddIssue( $patron->unblessed, $barcode );
2094
2095         # Simulate item marked as lost
2096         ModItem( { itemlost => 1 }, $biblio->biblionumber, $item_id );
2097         LostItem( $item_id, 1 );
2098
2099         my $processing_fee_lines = Koha::Account::Lines->search(
2100             { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'PF' } );
2101         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2102         my $processing_fee_line = $processing_fee_lines->next;
2103         is( $processing_fee_line->amount + 0,
2104             $processfee_amount, 'The right PF amount is generated' );
2105         is( $processing_fee_line->amountoutstanding + 0,
2106             $processfee_amount, 'The right PF amountoutstanding is generated' );
2107
2108         my $lost_fee_lines = Koha::Account::Lines->search(
2109             { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'L' } );
2110         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2111         my $lost_fee_line = $lost_fee_lines->next;
2112         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2113         is( $lost_fee_line->amountoutstanding + 0,
2114             $replacement_amount, 'The right L amountountstanding is generated' );
2115
2116         my $account = $patron->account;
2117         my $debts   = $account->outstanding_debits;
2118
2119         # Write off the debt
2120         my $credit = $account->add_credit(
2121             {   amount => $account->balance,
2122                 type   => 'payment'
2123             }
2124         );
2125         $credit->apply( { debits => $debts, offset_type => 'Payment' } );
2126
2127         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item_id, $patron->id );
2128         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2129
2130         is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2131         is( $credit_return->amount + 0,
2132             -99.00, 'The account line of type CR has an amount of -99' );
2133         is( $credit_return->amountoutstanding + 0,
2134             -99.00, 'The account line of type CR has an amountoutstanding of -99' );
2135
2136         $lost_fee_line->discard_changes;
2137         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2138         is( $lost_fee_line->accounttype,
2139             'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2140
2141         is( $patron->account->balance,
2142             -99, 'The patron balance is -99, a credit that equals the lost fee payment' );
2143     };
2144
2145     subtest 'Test without payment or write off' => sub {
2146
2147         plan tests => 12;
2148
2149         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2150         my $barcode = 'KD123456791';
2151
2152         my ( undef, undef, $item_id ) = AddItem(
2153             {   homebranch       => $library->branchcode,
2154                 holdingbranch    => $library->branchcode,
2155                 barcode          => $barcode,
2156                 replacementprice => $replacement_amount,
2157                 itype            => $item_type->itemtype
2158             },
2159             $biblio->biblionumber
2160         );
2161
2162         AddIssue( $patron->unblessed, $barcode );
2163
2164         # Simulate item marked as lost
2165         ModItem( { itemlost => 3 }, $biblio->biblionumber, $item_id );
2166         LostItem( $item_id, 1 );
2167
2168         my $processing_fee_lines = Koha::Account::Lines->search(
2169             { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'PF' } );
2170         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2171         my $processing_fee_line = $processing_fee_lines->next;
2172         is( $processing_fee_line->amount + 0,
2173             $processfee_amount, 'The right PF amount is generated' );
2174         is( $processing_fee_line->amountoutstanding + 0,
2175             $processfee_amount, 'The right PF amountoutstanding is generated' );
2176
2177         my $lost_fee_lines = Koha::Account::Lines->search(
2178             { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'L' } );
2179         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2180         my $lost_fee_line = $lost_fee_lines->next;
2181         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2182         is( $lost_fee_line->amountoutstanding + 0,
2183             $replacement_amount, 'The right L amountountstanding is generated' );
2184
2185         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item_id, $patron->id );
2186         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2187
2188         is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2189         is( $credit_return->amount + 0, -99.00, 'The account line of type CR has an amount of -99' );
2190         is( $credit_return->amountoutstanding + 0, 0, 'The account line of type CR has an amountoutstanding of 0' );
2191
2192         $lost_fee_line->discard_changes;
2193         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2194         is( $lost_fee_line->accounttype, 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2195
2196         is( $patron->account->balance, 20, 'The patron balance is 20, still owes the processing fee' );
2197     };
2198
2199     subtest 'Test with partial payement and write off, and remaining debt' => sub {
2200
2201         plan tests => 15;
2202
2203         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2204         my $barcode = 'KD123456792';
2205
2206         my ( undef, undef, $item_id ) = AddItem(
2207             {   homebranch       => $library->branchcode,
2208                 holdingbranch    => $library->branchcode,
2209                 barcode          => $barcode,
2210                 replacementprice => $replacement_amount,
2211                 itype            => $item_type->itemtype
2212             },
2213             $biblio->biblionumber
2214         );
2215
2216         AddIssue( $patron->unblessed, $barcode );
2217
2218         # Simulate item marked as lost
2219         ModItem( { itemlost => 1 }, $biblio->biblionumber, $item_id );
2220         LostItem( $item_id, 1 );
2221
2222         my $processing_fee_lines = Koha::Account::Lines->search(
2223             { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'PF' } );
2224         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2225         my $processing_fee_line = $processing_fee_lines->next;
2226         is( $processing_fee_line->amount + 0,
2227             $processfee_amount, 'The right PF amount is generated' );
2228         is( $processing_fee_line->amountoutstanding + 0,
2229             $processfee_amount, 'The right PF amountoutstanding is generated' );
2230
2231         my $lost_fee_lines = Koha::Account::Lines->search(
2232             { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'L' } );
2233         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2234         my $lost_fee_line = $lost_fee_lines->next;
2235         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2236         is( $lost_fee_line->amountoutstanding + 0,
2237             $replacement_amount, 'The right L amountountstanding is generated' );
2238
2239         my $account = $patron->account;
2240         is( $account->balance, $processfee_amount + $replacement_amount, 'Balance is PF + L' );
2241
2242         # Partially pay fee
2243         my $payment_amount = 27;
2244         my $payment        = $account->add_credit(
2245             {   amount => $payment_amount,
2246                 type   => 'payment'
2247             }
2248         );
2249
2250         $payment->apply( { debits => $lost_fee_lines->reset, offset_type => 'Payment' } );
2251
2252         # Partially write off fee
2253         my $write_off_amount = 25;
2254         my $write_off        = $account->add_credit(
2255             {   amount => $write_off_amount,
2256                 type   => 'writeoff'
2257             }
2258         );
2259         $write_off->apply( { debits => $lost_fee_lines->reset, offset_type => 'Writeoff' } );
2260
2261         is( $account->balance,
2262             $processfee_amount + $replacement_amount - $payment_amount - $write_off_amount,
2263             'Payment and write off applied'
2264         );
2265
2266         # Store the amountoutstanding value
2267         $lost_fee_line->discard_changes;
2268         my $outstanding = $lost_fee_line->amountoutstanding;
2269
2270         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item_id, $patron->id );
2271         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2272
2273         is( $account->balance, $processfee_amount - $payment_amount, 'Balance is PF - payment (CR)' );
2274
2275         $lost_fee_line->discard_changes;
2276         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2277         is( $lost_fee_line->accounttype,
2278             'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2279
2280         is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2281         is( $credit_return->amount + 0,
2282             ($payment_amount + $outstanding ) * -1,
2283             'The account line of type CR has an amount equal to the payment + outstanding'
2284         );
2285         is( $credit_return->amountoutstanding + 0,
2286             $payment_amount * -1,
2287             'The account line of type CR has an amountoutstanding equal to the payment'
2288         );
2289
2290         is( $account->balance,
2291             $processfee_amount - $payment_amount,
2292             'The patron balance is the difference between the PF and the credit'
2293         );
2294     };
2295
2296     subtest 'Partial payement, existing debits and AccountAutoReconcile' => sub {
2297
2298         plan tests => 8;
2299
2300         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2301         my $barcode = 'KD123456793';
2302         my $replacement_amount = 100;
2303         my $processfee_amount  = 20;
2304
2305         my $item_type          = $builder->build_object(
2306             {   class => 'Koha::ItemTypes',
2307                 value => {
2308                     notforloan         => undef,
2309                     rentalcharge       => 0,
2310                     defaultreplacecost => undef,
2311                     processfee         => 0
2312                 }
2313             }
2314         );
2315         my ( undef, undef, $item_id ) = AddItem(
2316             {   homebranch       => $library->branchcode,
2317                 holdingbranch    => $library->branchcode,
2318                 barcode          => $barcode,
2319                 replacementprice => $replacement_amount,
2320                 itype            => $item_type->itemtype
2321             },
2322             $biblionumber
2323         );
2324
2325         AddIssue( $patron->unblessed, $barcode );
2326
2327         # Simulate item marked as lost
2328         ModItem( { itemlost => 1 }, $biblionumber, $item_id );
2329         LostItem( $item_id, 1 );
2330
2331         my $lost_fee_lines = Koha::Account::Lines->search(
2332             { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'L' } );
2333         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2334         my $lost_fee_line = $lost_fee_lines->next;
2335         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2336         is( $lost_fee_line->amountoutstanding + 0,
2337             $replacement_amount, 'The right L amountountstanding is generated' );
2338
2339         my $account = $patron->account;
2340         is( $account->balance, $replacement_amount, 'Balance is L' );
2341
2342         # Partially pay fee
2343         my $payment_amount = 27;
2344         my $payment        = $account->add_credit(
2345             {   amount => $payment_amount,
2346                 type   => 'payment'
2347             }
2348         );
2349         $payment->apply({ debits => $lost_fee_lines->reset, offset_type => 'Payment' });
2350
2351         is( $account->balance,
2352             $replacement_amount - $payment_amount,
2353             'Payment applied'
2354         );
2355
2356         # TODO use add_debit when time comes
2357         my $manual_debit_amount = 80;
2358         C4::Accounts::manualinvoice( $patron->id, undef, undef, 'FU', $manual_debit_amount );
2359
2360         is( $account->balance, $manual_debit_amount + $replacement_amount - $payment_amount, 'Manual debit applied' );
2361
2362         t::lib::Mocks::mock_preference( 'AccountAutoReconcile', 1 );
2363
2364         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item_id, $patron->id );
2365         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2366
2367         is( $account->balance, $manual_debit_amount - $payment_amount, 'Balance is PF - payment (CR)' );
2368
2369         my $manual_debit = Koha::Account::Lines->search({ borrowernumber => $patron->id, accounttype => 'FU' })->next;
2370         is( $manual_debit->amountoutstanding + 0, $manual_debit_amount - $payment_amount, 'reconcile_balance was called' );
2371     };
2372 };
2373
2374 subtest '_FixOverduesOnReturn' => sub {
2375     plan tests => 10;
2376
2377     my $biblio = $builder->gimme_a_biblio({ author => 'Hall, Kylie' });
2378
2379     my $barcode = 'KD987654321';
2380     my $branchcode  = $library2->{branchcode};
2381
2382     my ( $item_bibnum, $item_bibitemnum, $itemnumber ) = AddItem(
2383         {
2384             homebranch       => $branchcode,
2385             holdingbranch    => $branchcode,
2386             barcode          => $barcode,
2387             replacementprice => 99.00,
2388             itype            => $itemtype
2389         },
2390         $biblio->biblionumber
2391     );
2392
2393     my $patron = $builder->build( { source => 'Borrower' } );
2394
2395     ## Start with basic call, should just close out the open fine
2396     my $accountline = Koha::Account::Line->new(
2397         {
2398             borrowernumber => $patron->{borrowernumber},
2399             accounttype    => 'FU',
2400             itemnumber     => $itemnumber,
2401             amount => 99.00,
2402             amountoutstanding => 99.00,
2403             lastincrement => 9.00,
2404         }
2405     )->store();
2406
2407     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $itemnumber );
2408
2409     $accountline->_result()->discard_changes();
2410
2411     is( $accountline->amountoutstanding, '99.000000', 'Fine has the same amount outstanding as previously' );
2412     is( $accountline->accounttype, 'F', 'Open fine ( account type FU ) has been closed out ( account type F )');
2413
2414
2415     ## Run again, with exemptfine enabled
2416     $accountline->set(
2417         {
2418             accounttype    => 'FU',
2419             amountoutstanding => 99.00,
2420         }
2421     )->store();
2422
2423     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $itemnumber, 1 );
2424
2425     $accountline->_result()->discard_changes();
2426     my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
2427
2428     is( $accountline->amountoutstanding + 0, 0, 'Fine has been reduced to 0' );
2429     is( $accountline->accounttype, 'FFOR', 'Open fine ( account type FU ) has been set to fine forgiven ( account type FFOR )');
2430     is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
2431     is( $offset->amount, '-99.000000', "Amount of offset is correct" );
2432
2433     ## Run again, with dropbox mode enabled
2434     $accountline->set(
2435         {
2436             accounttype    => 'FU',
2437             amountoutstanding => 99.00,
2438         }
2439     )->store();
2440
2441     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $itemnumber, 0, 1 );
2442
2443     $accountline->_result()->discard_changes();
2444     $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Dropbox' })->next();
2445
2446     is( $accountline->amountoutstanding + 0, 90, 'Fine has been reduced to 90' );
2447     is( $accountline->accounttype, 'F', 'Open fine ( account type FU ) has been closed out ( account type F )');
2448     is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via dropbox" );
2449     is( $offset->amount, '-9.000000', "Amount of offset is correct" );
2450 };
2451
2452 subtest 'Set waiting flag' => sub {
2453     plan tests => 4;
2454
2455     my $library_1 = $builder->build( { source => 'Branch' } );
2456     my $patron_1  = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2457     my $library_2 = $builder->build( { source => 'Branch' } );
2458     my $patron_2  = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2459
2460     my $biblio = $builder->build( { source => 'Biblio' } );
2461     my $biblioitem = $builder->build( { source => 'Biblioitem', value => { biblionumber => $biblio->{biblionumber} } } );
2462
2463     my $item = $builder->build(
2464         {
2465             source => 'Item',
2466             value  => {
2467                 homebranch    => $library_1->{branchcode},
2468                 holdingbranch => $library_1->{branchcode},
2469                 notforloan    => 0,
2470                 itemlost      => 0,
2471                 withdrawn     => 0,
2472                 biblionumber  => $biblioitem->{biblionumber},
2473             }
2474         }
2475     );
2476
2477     set_userenv( $library_2 );
2478     my $reserve_id = AddReserve(
2479         $library_2->{branchcode}, $patron_2->{borrowernumber}, $biblioitem->{biblionumber},
2480         '', 1, undef, undef, '', undef, $item->{itemnumber},
2481     );
2482
2483     set_userenv( $library_1 );
2484     my $do_transfer = 1;
2485     my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
2486     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2487     my $hold = Koha::Holds->find( $reserve_id );
2488     is( $hold->found, 'T', 'Hold is in transit' );
2489
2490     my ( $status ) = CheckReserves($item->{itemnumber});
2491     is( $status, 'Reserved', 'Hold is not waiting yet');
2492
2493     set_userenv( $library_2 );
2494     $do_transfer = 0;
2495     AddReturn( $item->{barcode}, $library_2->{branchcode} );
2496     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2497     $hold = Koha::Holds->find( $reserve_id );
2498     is( $hold->found, 'W', 'Hold is waiting' );
2499     ( $status ) = CheckReserves($item->{itemnumber});
2500     is( $status, 'Waiting', 'Now the hold is waiting');
2501 };
2502
2503 subtest 'CanBookBeIssued | is_overdue' => sub {
2504     plan tests => 3;
2505
2506     # Set a simple circ policy
2507     $dbh->do('DELETE FROM issuingrules');
2508     $dbh->do(
2509     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
2510                                     maxissueqty, issuelength, lengthunit,
2511                                     renewalsallowed, renewalperiod,
2512                                     norenewalbefore, auto_renew,
2513                                     fine, chargeperiod)
2514           VALUES (?, ?, ?, ?,
2515                   ?, ?, ?,
2516                   ?, ?,
2517                   ?, ?,
2518                   ?, ?
2519                  )
2520         },
2521         {},
2522         '*',   '*', '*', 25,
2523         1,     14,  'days',
2524         1,     7,
2525         undef, 0,
2526         .10,   1
2527     );
2528
2529     my $five_days_go = output_pref({ dt => dt_from_string->add( days => 5 ), dateonly => 1});
2530     my $ten_days_go  = output_pref({ dt => dt_from_string->add( days => 10), dateonly => 1 });
2531     my $library = $builder->build( { source => 'Branch' } );
2532     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2533
2534     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
2535     my $item = $builder->build(
2536         {
2537             source => 'Item',
2538             value  => {
2539                 homebranch    => $library->{branchcode},
2540                 holdingbranch => $library->{branchcode},
2541                 notforloan    => 0,
2542                 itemlost      => 0,
2543                 withdrawn     => 0,
2544                 biblionumber  => $biblioitem->{biblionumber},
2545             }
2546         }
2547     );
2548
2549     my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $five_days_go ); # date due was 10d ago
2550     my $actualissue = Koha::Checkouts->find( { itemnumber => $item->{itemnumber} } );
2551     is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
2552     my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->{barcode},$ten_days_go, undef, undef, undef);
2553     is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
2554     is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
2555 };
2556
2557 subtest 'ItemsDeniedRenewal preference' => sub {
2558     plan tests => 18;
2559
2560     C4::Context->set_preference('ItemsDeniedRenewal','');
2561
2562     my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
2563     $dbh->do(
2564         q{
2565         INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, maxissueqty, issuelength, lengthunit, renewalsallowed, renewalperiod,
2566                     norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
2567         },
2568         {},
2569         '*', $idr_lib->branchcode, '*', 25,
2570         20,  14,  'days',
2571         10,   7,
2572         undef,  0,
2573         .10, 1
2574     );
2575
2576     my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
2577         homebranch => $idr_lib->branchcode,
2578         withdrawn => 1,
2579         itype => 'HIDE',
2580         location => 'PROC',
2581         itemcallnumber => undef,
2582         itemnotes => "",
2583         }
2584     });
2585     my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
2586         homebranch => $idr_lib->branchcode,
2587         withdrawn => 0,
2588         itype => 'NOHIDE',
2589         location => 'NOPROC'
2590         }
2591     });
2592
2593     my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
2594         branchcode => $idr_lib->branchcode,
2595         }
2596     });
2597     my $future = dt_from_string->add( days => 1 );
2598     my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
2599         returndate => undef,
2600         renewals => 0,
2601         auto_renew => 0,
2602         borrowernumber => $idr_borrower->borrowernumber,
2603         itemnumber => $deny_book->itemnumber,
2604         onsite_checkout => 0,
2605         date_due => $future,
2606         }
2607     });
2608     my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
2609         returndate => undef,
2610         renewals => 0,
2611         auto_renew => 0,
2612         borrowernumber => $idr_borrower->borrowernumber,
2613         itemnumber => $allow_book->itemnumber,
2614         onsite_checkout => 0,
2615         date_due => $future,
2616         }
2617     });
2618
2619     my $idr_rules;
2620
2621     my ( $idr_mayrenew, $idr_error ) =
2622     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2623     is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
2624     is( $idr_error, undef, 'Renewal allowed when no rules' );
2625
2626     $idr_rules="withdrawn: [1]";
2627
2628     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2629     ( $idr_mayrenew, $idr_error ) =
2630     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2631     is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
2632     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
2633     ( $idr_mayrenew, $idr_error ) =
2634     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2635     is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
2636     is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
2637
2638     $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
2639
2640     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2641     ( $idr_mayrenew, $idr_error ) =
2642     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2643     is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
2644     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
2645     ( $idr_mayrenew, $idr_error ) =
2646     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2647     is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
2648     is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
2649
2650     $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
2651
2652     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2653     ( $idr_mayrenew, $idr_error ) =
2654     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2655     is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
2656     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
2657     ( $idr_mayrenew, $idr_error ) =
2658     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2659     is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
2660     is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
2661
2662     $idr_rules="itemcallnumber: [NULL]";
2663     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2664     ( $idr_mayrenew, $idr_error ) =
2665     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2666     is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
2667     $idr_rules="itemcallnumber: ['']";
2668     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2669     ( $idr_mayrenew, $idr_error ) =
2670     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2671     is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
2672
2673     $idr_rules="itemnotes: [NULL]";
2674     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2675     ( $idr_mayrenew, $idr_error ) =
2676     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2677     is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
2678     $idr_rules="itemnotes: ['']";
2679     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2680     ( $idr_mayrenew, $idr_error ) =
2681     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2682     is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
2683 };
2684
2685 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
2686     plan tests => 2;
2687
2688     t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
2689     my $library = $builder->build( { source => 'Branch' } );
2690     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
2691
2692     my $itemtype = $builder->build(
2693         {
2694             source => 'Itemtype',
2695             value  => { notforloan => undef, }
2696         }
2697     );
2698
2699     my $biblioitem = $builder->build( { source => 'Biblioitem', value => { itemtype => $itemtype->{itemtype} } } );
2700     my $item = $builder->build_object(
2701         {
2702             class => 'Koha::Items',
2703             value  => {
2704                 homebranch    => $library->{branchcode},
2705                 holdingbranch => $library->{branchcode},
2706                 notforloan    => 0,
2707                 itemlost      => 0,
2708                 withdrawn     => 0,
2709                 biblionumber  => $biblioitem->{biblionumber},
2710                 biblioitemnumber => $biblioitem->{biblioitemnumber},
2711             }
2712         }
2713     )->store;
2714
2715     my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2716     is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2717     is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2718 };
2719
2720 subtest 'CanBookBeIssued | notforloan' => sub {
2721     plan tests => 2;
2722
2723     t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
2724
2725     my $library = $builder->build( { source => 'Branch' } );
2726     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
2727
2728     my $itemtype = $builder->build(
2729         {
2730             source => 'Itemtype',
2731             value  => { notforloan => undef, }
2732         }
2733     );
2734
2735     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
2736     my $item = $builder->build_object(
2737         {
2738             class => 'Koha::Items',
2739             value  => {
2740                 homebranch    => $library->{branchcode},
2741                 holdingbranch => $library->{branchcode},
2742                 notforloan    => 0,
2743                 itemlost      => 0,
2744                 withdrawn     => 0,
2745                 itype         => $itemtype->{itemtype},
2746                 biblionumber  => $biblioitem->{biblionumber},
2747                 biblioitemnumber => $biblioitem->{biblioitemnumber},
2748             }
2749         }
2750     )->store;
2751
2752     my ( $issuingimpossible, $needsconfirmation );
2753
2754
2755     subtest 'item-level_itypes = 1' => sub {
2756         plan tests => 6;
2757
2758         t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
2759         # Is for loan at item type and item level
2760         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2761         is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2762         is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2763
2764         # not for loan at item type level
2765         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
2766         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2767         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2768         is_deeply(
2769             $issuingimpossible,
2770             { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
2771             'Item can not be issued, not for loan at item type level'
2772         );
2773
2774         # not for loan at item level
2775         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
2776         $item->notforloan( 1 )->store;
2777         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2778         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2779         is_deeply(
2780             $issuingimpossible,
2781             { NOT_FOR_LOAN => 1, item_notforloan => 1 },
2782             'Item can not be issued, not for loan at item type level'
2783         );
2784     };
2785
2786     subtest 'item-level_itypes = 0' => sub {
2787         plan tests => 6;
2788
2789         t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
2790
2791         # We set another itemtype for biblioitem
2792         my $itemtype = $builder->build(
2793             {
2794                 source => 'Itemtype',
2795                 value  => { notforloan => undef, }
2796             }
2797         );
2798
2799         # for loan at item type and item level
2800         $item->notforloan(0)->store;
2801         $item->biblioitem->itemtype($itemtype->{itemtype})->store;
2802         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2803         is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2804         is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2805
2806         # not for loan at item type level
2807         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
2808         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2809         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2810         is_deeply(
2811             $issuingimpossible,
2812             { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
2813             'Item can not be issued, not for loan at item type level'
2814         );
2815
2816         # not for loan at item level
2817         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
2818         $item->notforloan( 1 )->store;
2819         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2820         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2821         is_deeply(
2822             $issuingimpossible,
2823             { NOT_FOR_LOAN => 1, item_notforloan => 1 },
2824             'Item can not be issued, not for loan at item type level'
2825         );
2826     };
2827
2828     # TODO test with AllowNotForLoanOverride = 1
2829 };
2830
2831 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
2832     plan tests => 1;
2833
2834     t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
2835     my $item = $builder->build_object({ class => 'Koha::Items', value  => { onloan => '2018-01-01' }});
2836     AddReturn( $item->barcode, $item->homebranch );
2837     $item->discard_changes; # refresh
2838     is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
2839 };
2840
2841 $schema->storage->txn_rollback;
2842 C4::Context->clear_syspref_cache();
2843 $cache->clear_from_cache('single_holidays');
2844
2845 sub set_userenv {
2846     my ( $library ) = @_;
2847     t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
2848 }
2849
2850 sub str {
2851     my ( $error, $question, $alert ) = @_;
2852     my $s;
2853     $s  = %$error    ? ' (error: '    . join( ' ', keys %$error    ) . ')' : '';
2854     $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
2855     $s .= %$alert    ? ' (alert: '    . join( ' ', keys %$alert    ) . ')' : '';
2856     return $s;
2857 }
2858
2859 sub test_debarment_on_checkout {
2860     my ($params) = @_;
2861     my $item     = $params->{item};
2862     my $library  = $params->{library};
2863     my $patron   = $params->{patron};
2864     my $due_date = $params->{due_date} || dt_from_string;
2865     my $return_date = $params->{return_date} || dt_from_string;
2866     my $expected_expiration_date = $params->{expiration_date};
2867
2868     $expected_expiration_date = output_pref(
2869         {
2870             dt         => $expected_expiration_date,
2871             dateformat => 'sql',
2872             dateonly   => 1,
2873         }
2874     );
2875     my @caller      = caller;
2876     my $line_number = $caller[2];
2877     AddIssue( $patron, $item->{barcode}, $due_date );
2878
2879     my ( undef, $message ) = AddReturn( $item->{barcode}, $library->{branchcode},
2880         undef, undef, $return_date );
2881     is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' )
2882         or diag('AddReturn returned message ' . Dumper $message );
2883     my $debarments = Koha::Patron::Debarments::GetDebarments(
2884         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2885     is( scalar(@$debarments), 1, 'Test at line ' . $line_number );
2886
2887     is( $debarments->[0]->{expiration},
2888         $expected_expiration_date, 'Test at line ' . $line_number );
2889     Koha::Patron::Debarments::DelUniqueDebarment(
2890         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2891 }