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