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