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