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