Bug 14390 [QA Followup] - Unit Test
[koha.git] / t / db_dependent / Circulation.t
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19
20 use DateTime;
21 use t::lib::Mocks;
22 use C4::Biblio;
23 use C4::Branch;
24 use C4::Items;
25 use C4::Members;
26 use C4::Reserves;
27 use C4::Overdues qw(UpdateFine CalcFine);
28 use Koha::DateUtils;
29 use Koha::Database;
30
31 use t::lib::TestBuilder;
32
33 use Test::More tests => 85;
34
35 BEGIN {
36     use_ok('C4::Circulation');
37 }
38
39 my $schema = Koha::Database->schema;
40 $schema->storage->txn_begin;
41 my $builder = t::lib::TestBuilder->new;
42 my $dbh = C4::Context->dbh;
43
44 # Start transaction
45 $dbh->{RaiseError} = 1;
46
47 # Start with a clean slate
48 $dbh->do('DELETE FROM issues');
49
50 my $library = $builder->build({
51     source => 'Branch',
52 });
53 my $library2 = $builder->build({
54     source => 'Branch',
55 });
56
57 my $CircControl = C4::Context->preference('CircControl');
58 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
59
60 my $item = {
61     homebranch => $library2->{branchcode},
62     holdingbranch => $library2->{branchcode}
63 };
64
65 my $borrower = {
66     branchcode => $library2->{branchcode}
67 };
68
69 # No userenv, PickupLibrary
70 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
71 is(
72     C4::Context->preference('CircControl'),
73     'PickupLibrary',
74     'CircControl changed to PickupLibrary'
75 );
76 is(
77     C4::Circulation::_GetCircControlBranch($item, $borrower),
78     $item->{$HomeOrHoldingBranch},
79     '_GetCircControlBranch returned item branch (no userenv defined)'
80 );
81
82 # No userenv, PatronLibrary
83 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
84 is(
85     C4::Context->preference('CircControl'),
86     'PatronLibrary',
87     'CircControl changed to PatronLibrary'
88 );
89 is(
90     C4::Circulation::_GetCircControlBranch($item, $borrower),
91     $borrower->{branchcode},
92     '_GetCircControlBranch returned borrower branch'
93 );
94
95 # No userenv, ItemHomeLibrary
96 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
97 is(
98     C4::Context->preference('CircControl'),
99     'ItemHomeLibrary',
100     'CircControl changed to ItemHomeLibrary'
101 );
102 is(
103     $item->{$HomeOrHoldingBranch},
104     C4::Circulation::_GetCircControlBranch($item, $borrower),
105     '_GetCircControlBranch returned item branch'
106 );
107
108 # Now, set a userenv
109 C4::Context->_new_userenv('xxx');
110 C4::Context->set_userenv(0,0,0,'firstname','surname', $library2->{branchcode}, 'Midway Public Library', '', '', '');
111 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
112
113 # Userenv set, PickupLibrary
114 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
115 is(
116     C4::Context->preference('CircControl'),
117     'PickupLibrary',
118     'CircControl changed to PickupLibrary'
119 );
120 is(
121     C4::Circulation::_GetCircControlBranch($item, $borrower),
122     $library2->{branchcode},
123     '_GetCircControlBranch returned current branch'
124 );
125
126 # Userenv set, PatronLibrary
127 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
128 is(
129     C4::Context->preference('CircControl'),
130     'PatronLibrary',
131     'CircControl changed to PatronLibrary'
132 );
133 is(
134     C4::Circulation::_GetCircControlBranch($item, $borrower),
135     $borrower->{branchcode},
136     '_GetCircControlBranch returned borrower branch'
137 );
138
139 # Userenv set, ItemHomeLibrary
140 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
141 is(
142     C4::Context->preference('CircControl'),
143     'ItemHomeLibrary',
144     'CircControl changed to ItemHomeLibrary'
145 );
146 is(
147     C4::Circulation::_GetCircControlBranch($item, $borrower),
148     $item->{$HomeOrHoldingBranch},
149     '_GetCircControlBranch returned item branch'
150 );
151
152 # Reset initial configuration
153 t::lib::Mocks::mock_preference('CircControl', $CircControl);
154 is(
155     C4::Context->preference('CircControl'),
156     $CircControl,
157     'CircControl reset to its initial value'
158 );
159
160 # Set a simple circ policy
161 $dbh->do('DELETE FROM issuingrules');
162 $dbh->do(
163     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
164                                 maxissueqty, issuelength, lengthunit,
165                                 renewalsallowed, renewalperiod,
166                                 norenewalbefore, auto_renew,
167                                 fine, chargeperiod)
168       VALUES (?, ?, ?, ?,
169               ?, ?, ?,
170               ?, ?,
171               ?, ?,
172               ?, ?
173              )
174     },
175     {},
176     '*', '*', '*', 25,
177     20, 14, 'days',
178     1, 7,
179     undef, 0,
180     .10, 1
181 );
182
183 # Test C4::Circulation::ProcessOfflinePayment
184 my $sth = C4::Context->dbh->prepare("SELECT COUNT(*) FROM accountlines WHERE amount = '-123.45' AND accounttype = 'Pay'");
185 $sth->execute();
186 my ( $original_count ) = $sth->fetchrow_array();
187
188 C4::Context->dbh->do("INSERT INTO borrowers ( cardnumber, surname, firstname, categorycode, branchcode ) VALUES ( '99999999999', 'Hall', 'Kyle', 'S', ? )", undef, $library2->{branchcode} );
189
190 C4::Circulation::ProcessOfflinePayment({ cardnumber => '99999999999', amount => '123.45' });
191
192 $sth->execute();
193 my ( $new_count ) = $sth->fetchrow_array();
194
195 ok( $new_count == $original_count  + 1, 'ProcessOfflinePayment makes payment correctly' );
196
197 C4::Context->dbh->do("DELETE FROM accountlines WHERE borrowernumber IN ( SELECT borrowernumber FROM borrowers WHERE cardnumber = '99999999999' )");
198 C4::Context->dbh->do("DELETE FROM borrowers WHERE cardnumber = '99999999999'");
199 C4::Context->dbh->do("DELETE FROM accountlines");
200 {
201 # CanBookBeRenewed tests
202
203     # Generate test biblio
204     my $biblio = MARC::Record->new();
205     my $title = 'Silence in the library';
206     $biblio->append_fields(
207         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
208         MARC::Field->new('245', ' ', ' ', a => $title),
209     );
210
211     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
212
213     my $barcode = 'R00000342';
214     my $branch = $library2->{branchcode};
215
216     my ( $item_bibnum, $item_bibitemnum, $itemnumber ) = AddItem(
217         {
218             homebranch       => $branch,
219             holdingbranch    => $branch,
220             barcode          => $barcode,
221             replacementprice => 12.00
222         },
223         $biblionumber
224     );
225
226     my $barcode2 = 'R00000343';
227     my ( $item_bibnum2, $item_bibitemnum2, $itemnumber2 ) = AddItem(
228         {
229             homebranch       => $branch,
230             holdingbranch    => $branch,
231             barcode          => $barcode2,
232             replacementprice => 23.00
233         },
234         $biblionumber
235     );
236
237     my $barcode3 = 'R00000346';
238     my ( $item_bibnum3, $item_bibitemnum3, $itemnumber3 ) = AddItem(
239         {
240             homebranch       => $branch,
241             holdingbranch    => $branch,
242             barcode          => $barcode3,
243             replacementprice => 23.00
244         },
245         $biblionumber
246     );
247
248
249
250
251     # Create borrowers
252     my %renewing_borrower_data = (
253         firstname =>  'John',
254         surname => 'Renewal',
255         categorycode => 'S',
256         branchcode => $branch,
257     );
258
259     my %reserving_borrower_data = (
260         firstname =>  'Katrin',
261         surname => 'Reservation',
262         categorycode => 'S',
263         branchcode => $branch,
264     );
265
266     my %hold_waiting_borrower_data = (
267         firstname =>  'Kyle',
268         surname => 'Reservation',
269         categorycode => 'S',
270         branchcode => $branch,
271     );
272
273     my %restricted_borrower_data = (
274         firstname =>  'Alice',
275         surname => 'Reservation',
276         categorycode => 'S',
277         debarred => '3228-01-01',
278         branchcode => $branch,
279     );
280
281     my $renewing_borrowernumber = AddMember(%renewing_borrower_data);
282     my $reserving_borrowernumber = AddMember(%reserving_borrower_data);
283     my $hold_waiting_borrowernumber = AddMember(%hold_waiting_borrower_data);
284     my $restricted_borrowernumber = AddMember(%restricted_borrower_data);
285
286     my $renewing_borrower = GetMember( borrowernumber => $renewing_borrowernumber );
287     my $restricted_borrower = GetMember( borrowernumber => $restricted_borrowernumber );
288
289     my $bibitems       = '';
290     my $priority       = '1';
291     my $resdate        = undef;
292     my $expdate        = undef;
293     my $notes          = '';
294     my $checkitem      = undef;
295     my $found          = undef;
296
297     my $issue = AddIssue( $renewing_borrower, $barcode);
298     my $datedue = dt_from_string( $issue->date_due() );
299     is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
300
301     my $issue2 = AddIssue( $renewing_borrower, $barcode2);
302     $datedue = dt_from_string( $issue->date_due() );
303     is (defined $issue2, 1, "Item 2 checked out, due date: " . $issue2->date_due());
304
305
306     my $borrowing_borrowernumber = GetItemIssue($itemnumber)->{borrowernumber};
307     is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
308
309     my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber, 1);
310     is( $renewokay, 1, 'Can renew, no holds for this title or item');
311
312
313     # Biblio-level hold, renewal test
314     AddReserve(
315         $branch, $reserving_borrowernumber, $biblionumber,
316         $bibitems,  $priority, $resdate, $expdate, $notes,
317         $title, $checkitem, $found
318     );
319
320     # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
321     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
322     t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
323     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
324     is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
325     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
326     is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
327
328     # Now let's add an item level hold, we should no longer be able to renew the item
329     my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
330         {
331             borrowernumber => $hold_waiting_borrowernumber,
332             biblionumber   => $biblionumber,
333             itemnumber     => $itemnumber,
334             branchcode     => $branch,
335             priority       => 3,
336         }
337     );
338     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
339     is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
340     $hold->delete();
341
342     # 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
343     # be able to renew these items
344     $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
345         {
346             borrowernumber => $hold_waiting_borrowernumber,
347             biblionumber   => $biblionumber,
348             itemnumber     => $itemnumber3,
349             branchcode     => $branch,
350             priority       => 0,
351             found          => 'W'
352         }
353     );
354     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
355     is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
356     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
357     is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
358     t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
359
360     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
361     is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
362     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
363
364     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
365     is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
366     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
367
368     my $reserveid = C4::Reserves::GetReserveId({ biblionumber => $biblionumber, borrowernumber => $reserving_borrowernumber});
369     my $reserving_borrower = GetMember( borrowernumber => $reserving_borrowernumber );
370     AddIssue($reserving_borrower, $barcode3);
371     my $reserve = $dbh->selectrow_hashref(
372         'SELECT * FROM old_reserves WHERE reserve_id = ?',
373         { Slice => {} },
374         $reserveid
375     );
376     is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
377
378     # Item-level hold, renewal test
379     AddReserve(
380         $branch, $reserving_borrowernumber, $biblionumber,
381         $bibitems,  $priority, $resdate, $expdate, $notes,
382         $title, $itemnumber, $found
383     );
384
385     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber, 1);
386     is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
387     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
388
389     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2, 1);
390     is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
391
392     # Items can't fill hold for reasons
393     ModItem({ notforloan => 1 }, $biblionumber, $itemnumber);
394     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber, 1);
395     is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
396     ModItem({ notforloan => 0, itype => '' }, $biblionumber, $itemnumber,1);
397
398     # FIXME: Add more for itemtype not for loan etc.
399
400     # Restricted users cannot renew when RestrictionBlockRenewing is enabled
401     my $barcode5 = 'R00000347';
402     my ( $item_bibnum5, $item_bibitemnum5, $itemnumber5 ) = AddItem(
403         {
404             homebranch       => $branch,
405             holdingbranch    => $branch,
406             barcode          => $barcode5,
407             replacementprice => 23.00
408         },
409         $biblionumber
410     );
411     my $datedue5 = AddIssue($restricted_borrower, $barcode5);
412     is (defined $datedue5, 1, "Item with date due checked out, due date: $datedue5");
413
414     t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
415     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
416     is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
417     ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrowernumber, $itemnumber5);
418     is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
419
420     # Users cannot renew an overdue item
421     my $barcode6 = 'R00000348';
422     my ( $item_bibnum6, $item_bibitemnum6, $itemnumber6 ) = AddItem(
423         {
424             homebranch       => $branch,
425             holdingbranch    => $branch,
426             barcode          => $barcode6,
427             replacementprice => 23.00
428         },
429         $biblionumber
430     );
431
432     my $barcode7 = 'R00000349';
433     my ( $item_bibnum7, $item_bibitemnum7, $itemnumber7 ) = AddItem(
434         {
435             homebranch       => $branch,
436             holdingbranch    => $branch,
437             barcode          => $barcode7,
438             replacementprice => 23.00
439         },
440         $biblionumber
441     );
442     my $datedue6 = AddIssue( $renewing_borrower, $barcode6);
443     is (defined $datedue6, 1, "Item 2 checked out, due date: $datedue6");
444
445     my $now = dt_from_string();
446     my $five_weeks = DateTime::Duration->new(weeks => 5);
447     my $five_weeks_ago = $now - $five_weeks;
448
449     my $passeddatedue1 = AddIssue($renewing_borrower, $barcode7, $five_weeks_ago);
450     is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: " . $passeddatedue1->date_due);
451
452     my ( $fine ) = CalcFine( GetItem(undef, $barcode7), $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
453     C4::Overdues::UpdateFine(
454         $itemnumber7,
455         $renewing_borrower->{borrowernumber},
456         $fine,
457         'FU',
458         Koha::DateUtils::output_pref($five_weeks_ago)
459     );
460     AddRenewal( $renewing_borrower->{borrowernumber}, $itemnumber7, $branch );
461     $fine = $schema->resultset('Accountline')->single( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $itemnumber7 } );
462     is( $fine->accounttype, 'F', 'Fine on renewed item is closed out properly' );
463     $fine->delete();
464
465     t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
466     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber6);
467     is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
468     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber7);
469     is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
470
471
472     $reserveid = C4::Reserves::GetReserveId({ biblionumber => $biblionumber, itemnumber => $itemnumber, borrowernumber => $reserving_borrowernumber});
473     CancelReserve({ reserve_id => $reserveid });
474
475     # Test automatic renewal before value for "norenewalbefore" in policy is set
476     my $barcode4 = '11235813';
477     my ( $item_bibnum4, $item_bibitemnum4, $itemnumber4 ) = AddItem(
478         {
479             homebranch       => $branch,
480             holdingbranch    => $branch,
481             barcode          => $barcode4,
482             replacementprice => 16.00
483         },
484         $biblionumber
485     );
486
487     AddIssue( $renewing_borrower, $barcode4, undef, undef, undef, undef, { auto_renew => 1 } );
488     ( $renewokay, $error ) =
489       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
490     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
491     is( $error, 'auto_too_soon',
492         'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
493
494     # set policy to require that loans cannot be
495     # renewed until seven days prior to the due date
496     $dbh->do('UPDATE issuingrules SET norenewalbefore = 7');
497     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
498     is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
499     is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
500     is(
501         GetSoonestRenewDate($renewing_borrowernumber, $itemnumber),
502         $datedue->clone->add(days => -7),
503         'Bug 7413: Renewals permitted 7 days before due date, as expected',
504     );
505
506     # Test automatic renewal again
507     ( $renewokay, $error ) =
508       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
509     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
510     is( $error, 'auto_too_soon',
511 'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
512     );
513
514     # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
515     # and test automatic renewal again
516     $dbh->do('UPDATE issuingrules SET norenewalbefore = 0');
517     ( $renewokay, $error ) =
518       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
519     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
520     is( $error, 'auto_too_soon',
521 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
522     );
523
524     # Change policy so that loans can be renewed 99 days prior to the due date
525     # and test automatic renewal again
526     $dbh->do('UPDATE issuingrules SET norenewalbefore = 99');
527     ( $renewokay, $error ) =
528       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
529     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
530     is( $error, 'auto_renew',
531 'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
532     );
533
534     # Too many renewals
535
536     # set policy to forbid renewals
537     $dbh->do('UPDATE issuingrules SET norenewalbefore = NULL, renewalsallowed = 0');
538
539     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
540     is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
541     is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
542
543     # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
544     t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
545     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
546
547     C4::Overdues::UpdateFine( $itemnumber, $renewing_borrower->{borrowernumber},
548         15.00, q{}, Koha::DateUtils::output_pref($datedue) );
549
550     LostItem( $itemnumber, 1 );
551
552     my $item = Koha::Database->new()->schema()->resultset('Item')->find($itemnumber);
553     ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
554
555     my $total_due = $dbh->selectrow_array(
556         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
557         undef, $renewing_borrower->{borrowernumber}
558     );
559
560     ok( $total_due == 12, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
561
562     C4::Context->dbh->do("DELETE FROM accountlines");
563
564     t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
565     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
566
567     C4::Overdues::UpdateFine( $itemnumber2, $renewing_borrower->{borrowernumber},
568         15.00, q{}, Koha::DateUtils::output_pref($datedue) );
569
570     LostItem( $itemnumber2, 0 );
571
572     my $item2 = Koha::Database->new()->schema()->resultset('Item')->find($itemnumber2);
573     ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
574
575     $total_due = $dbh->selectrow_array(
576         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
577         undef, $renewing_borrower->{borrowernumber}
578     );
579
580     ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
581
582     my $future = dt_from_string();
583     $future->add( days => 7 );
584     my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
585     ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
586
587     # Users cannot renew any item if there is an overdue item
588     t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
589     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber6);
590     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
591     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber7);
592     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
593
594   }
595
596 {
597     # GetUpcomingDueIssues tests
598     my $barcode  = 'R00000342';
599     my $barcode2 = 'R00000343';
600     my $barcode3 = 'R00000344';
601     my $branch   = $library2->{branchcode};
602
603     #Create another record
604     my $biblio2 = MARC::Record->new();
605     my $title2 = 'Something is worng here';
606     $biblio2->append_fields(
607         MARC::Field->new('100', ' ', ' ', a => 'Anonymous'),
608         MARC::Field->new('245', ' ', ' ', a => $title2),
609     );
610     my ($biblionumber2, $biblioitemnumber2) = AddBiblio($biblio2, '');
611
612     #Create third item
613     AddItem(
614         {
615             homebranch       => $branch,
616             holdingbranch    => $branch,
617             barcode          => $barcode3
618         },
619         $biblionumber2
620     );
621
622     # Create a borrower
623     my %a_borrower_data = (
624         firstname =>  'Fridolyn',
625         surname => 'SOMERS',
626         categorycode => 'S',
627         branchcode => $branch,
628     );
629
630     my $a_borrower_borrowernumber = AddMember(%a_borrower_data);
631     my $a_borrower = GetMember( borrowernumber => $a_borrower_borrowernumber );
632
633     my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
634     my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
635     my $today = DateTime->today(time_zone => C4::Context->tz());
636
637     my $issue = AddIssue( $a_borrower, $barcode, $yesterday );
638     my $datedue = dt_from_string( $issue->date_due() );
639     my $issue2 = AddIssue( $a_borrower, $barcode2, $two_days_ahead );
640     my $datedue2 = dt_from_string( $issue->date_due() );
641
642     my $upcoming_dues;
643
644     # GetUpcomingDueIssues tests
645     for my $i(0..1) {
646         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
647         is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
648     }
649
650     #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
651     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
652     is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
653
654     for my $i(3..5) {
655         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
656         is ( scalar( @$upcoming_dues ), 1,
657             "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
658     }
659
660     # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
661
662     my $issue3 = AddIssue( $a_borrower, $barcode3, $today );
663
664     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
665     is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
666
667     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
668     is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
669
670     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
671     is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
672
673     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 }  );
674     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
675
676     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
677     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
678
679     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
680     is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
681
682 }
683
684 {
685     my $barcode  = '1234567890';
686     my $branch   = $library2->{branchcode};
687
688     my $biblio = MARC::Record->new();
689     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
690
691     #Create third item
692     my ( undef, undef, $itemnumber ) = AddItem(
693         {
694             homebranch       => $branch,
695             holdingbranch    => $branch,
696             barcode          => $barcode
697         },
698         $biblionumber
699     );
700
701     # Create a borrower
702     my %a_borrower_data = (
703         firstname =>  'Kyle',
704         surname => 'Hall',
705         categorycode => 'S',
706         branchcode => $branch,
707     );
708
709     my $borrowernumber = AddMember(%a_borrower_data);
710
711     UpdateFine( $itemnumber, $borrowernumber, 0 );
712
713     my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $itemnumber );
714     my $count = $hr->{count};
715
716     is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
717 }
718
719 {
720     $dbh->do('DELETE FROM issues');
721     $dbh->do('DELETE FROM items');
722     $dbh->do('DELETE FROM issuingrules');
723     $dbh->do(
724         q{
725         INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, maxissueqty, issuelength, lengthunit, renewalsallowed, renewalperiod,
726                     norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
727         },
728         {},
729         '*', '*', '*', 25,
730         20,  14,  'days',
731         1,   7,
732         undef,  0,
733         .10, 1
734     );
735     my $biblio = MARC::Record->new();
736     my ( $biblionumber, $biblioitemnumber ) = AddBiblio( $biblio, '' );
737
738     my $barcode1 = '1234';
739     my ( undef, undef, $itemnumber1 ) = AddItem(
740         {
741             homebranch    => $library2->{branchcode},
742             holdingbranch => $library2->{branchcode},
743             barcode       => $barcode1,
744         },
745         $biblionumber
746     );
747     my $barcode2 = '4321';
748     my ( undef, undef, $itemnumber2 ) = AddItem(
749         {
750             homebranch    => $library2->{branchcode},
751             holdingbranch => $library2->{branchcode},
752             barcode       => $barcode2,
753         },
754         $biblionumber
755     );
756
757     my $borrowernumber1 = AddMember(
758         firstname    => 'Kyle',
759         surname      => 'Hall',
760         categorycode => 'S',
761         branchcode   => $library2->{branchcode},
762     );
763     my $borrowernumber2 = AddMember(
764         firstname    => 'Chelsea',
765         surname      => 'Hall',
766         categorycode => 'S',
767         branchcode   => $library2->{branchcode},
768     );
769
770     my $borrower1 = GetMember( borrowernumber => $borrowernumber1 );
771     my $borrower2 = GetMember( borrowernumber => $borrowernumber2 );
772
773     my $issue = AddIssue( $borrower1, $barcode1 );
774
775     my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
776     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
777
778     AddReserve(
779         $library2->{branchcode}, $borrowernumber2, $biblionumber,
780         '',  1, undef, undef, '',
781         undef, undef, undef
782     );
783
784     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
785     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
786     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
787     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
788
789     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
790     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
791     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
792     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
793
794     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
795     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
796     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
797     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
798
799     C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
800     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
801     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
802     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
803
804     # Setting item not checked out to be not for loan but holdable
805     ModItem({ notforloan => -1 }, $biblionumber, $itemnumber2);
806
807     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $itemnumber1 );
808     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' );
809 }
810
811 {
812     # Don't allow renewing onsite checkout
813     my $barcode  = 'R00000XXX';
814     my $branch   = $library->{branchcode};
815
816     #Create another record
817     my $biblio = MARC::Record->new();
818     $biblio->append_fields(
819         MARC::Field->new('100', ' ', ' ', a => 'Anonymous'),
820         MARC::Field->new('245', ' ', ' ', a => 'A title'),
821     );
822     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
823
824     my (undef, undef, $itemnumber) = AddItem(
825         {
826             homebranch       => $branch,
827             holdingbranch    => $branch,
828             barcode          => $barcode,
829         },
830         $biblionumber
831     );
832
833     my $borrowernumber = AddMember(
834         firstname =>  'fn',
835         surname => 'dn',
836         categorycode => 'S',
837         branchcode => $branch,
838     );
839
840     my $borrower = GetMember( borrowernumber => $borrowernumber );
841     my $issue = AddIssue( $borrower, $barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
842     my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $itemnumber );
843     is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
844     is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
845 }
846
847 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
848     plan tests => 23;
849
850     my $homebranch    = $builder->build( { source => 'Branch' } );
851     my $holdingbranch = $builder->build( { source => 'Branch' } );
852     my $otherbranch   = $builder->build( { source => 'Branch' } );
853     my $patron_1      = $builder->build( { source => 'Borrower' } );
854     my $patron_2      = $builder->build( { source => 'Borrower' } );
855
856     # CanBookBeIssued needs its $borrower parameter to come from
857     # GetMemberDetails
858     $patron_2 = GetMemberDetails($patron_2->{borrowernumber});
859
860     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
861     my $item = $builder->build(
862         {   source => 'Item',
863             value  => {
864                 homebranch    => $homebranch->{branchcode},
865                 holdingbranch => $holdingbranch->{branchcode},
866                 notforloan    => 0,
867                 itemlost      => 0,
868                 withdrawn     => 0,
869                 biblionumber  => $biblioitem->{biblionumber}
870             }
871         }
872     );
873
874     set_userenv($holdingbranch);
875
876     my $issue = AddIssue( $patron_1, $item->{barcode} );
877     is( ref($issue), 'Koha::Schema::Result::Issue' );    # FIXME Should be Koha::Issue
878
879     my ( $error, $question, $alerts );
880
881     # AllowReturnToBranch == anywhere
882     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
883     ## Can be issued from homebranch
884     set_userenv($homebranch);
885     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
886     is( keys(%$error) + keys(%$alerts),        0 );
887     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
888     ## Can be issued from holdingbranch
889     set_userenv($holdingbranch);
890     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
891     is( keys(%$error) + keys(%$alerts),        0 );
892     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
893     ## Can be issued from another branch
894     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
895     is( keys(%$error) + keys(%$alerts),        0 );
896     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
897
898     # AllowReturnToBranch == holdingbranch
899     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
900     ## Cannot be issued from homebranch
901     set_userenv($homebranch);
902     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
903     is( keys(%$question) + keys(%$alerts),  0 );
904     is( exists $error->{RETURN_IMPOSSIBLE}, 1 );
905     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
906     ## Can be issued from holdinbranch
907     set_userenv($holdingbranch);
908     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
909     is( keys(%$error) + keys(%$alerts),        0 );
910     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
911     ## Cannot be issued from another branch
912     set_userenv($otherbranch);
913     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
914     is( keys(%$question) + keys(%$alerts),  0 );
915     is( exists $error->{RETURN_IMPOSSIBLE}, 1 );
916     is( $error->{branch_to_return},         $holdingbranch->{branchcode} );
917
918     # AllowReturnToBranch == homebranch
919     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
920     ## Can be issued from holdinbranch
921     set_userenv($homebranch);
922     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
923     is( keys(%$error) + keys(%$alerts),        0 );
924     is( exists $question->{ISSUED_TO_ANOTHER}, 1 );
925     ## Cannot be issued from holdinbranch
926     set_userenv($holdingbranch);
927     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
928     is( keys(%$question) + keys(%$alerts),  0 );
929     is( exists $error->{RETURN_IMPOSSIBLE}, 1 );
930     is( $error->{branch_to_return},         $homebranch->{branchcode} );
931     ## Cannot be issued from holdinbranch
932     set_userenv($otherbranch);
933     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
934     is( keys(%$question) + keys(%$alerts),  0 );
935     is( exists $error->{RETURN_IMPOSSIBLE}, 1 );
936     is( $error->{branch_to_return},         $homebranch->{branchcode} );
937
938     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
939 };
940
941 subtest 'AddIssue & AllowReturnToBranch' => sub {
942     plan tests => 9;
943
944     my $homebranch    = $builder->build( { source => 'Branch' } );
945     my $holdingbranch = $builder->build( { source => 'Branch' } );
946     my $otherbranch   = $builder->build( { source => 'Branch' } );
947     my $patron_1      = $builder->build( { source => 'Borrower' } );
948     my $patron_2      = $builder->build( { source => 'Borrower' } );
949
950     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
951     my $item = $builder->build(
952         {   source => 'Item',
953             value  => {
954                 homebranch    => $homebranch->{branchcode},
955                 holdingbranch => $holdingbranch->{branchcode},
956                 notforloan    => 0,
957                 itemlost      => 0,
958                 withdrawn     => 0,
959                 biblionumber  => $biblioitem->{biblionumber}
960             }
961         }
962     );
963
964     set_userenv($holdingbranch);
965
966     my $ref_issue = 'Koha::Schema::Result::Issue'; # FIXME Should be Koha::Issue
967     my $issue = AddIssue( $patron_1, $item->{barcode} );
968
969     my ( $error, $question, $alerts );
970
971     # AllowReturnToBranch == homebranch
972     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
973     ## Can be issued from homebranch
974     set_userenv($homebranch);
975     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
976     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
977     ## Can be issued from holdinbranch
978     set_userenv($holdingbranch);
979     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
980     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
981     ## Can be issued from another branch
982     set_userenv($otherbranch);
983     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
984     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
985
986     # AllowReturnToBranch == holdinbranch
987     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
988     ## Cannot be issued from homebranch
989     set_userenv($homebranch);
990     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
991     ## Can be issued from holdingbranch
992     set_userenv($holdingbranch);
993     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
994     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
995     ## Cannot be issued from another branch
996     set_userenv($otherbranch);
997     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
998
999     # AllowReturnToBranch == homebranch
1000     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1001     ## Can be issued from homebranch
1002     set_userenv($homebranch);
1003     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1004     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1005     ## Cannot be issued from holdinbranch
1006     set_userenv($holdingbranch);
1007     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1008     ## Cannot be issued from another branch
1009     set_userenv($otherbranch);
1010     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1011     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1012 };
1013
1014
1015 sub set_userenv {
1016     my ( $library ) = @_;
1017     C4::Context->set_userenv(0,0,0,'firstname','surname', $library->{branchcode}, $library->{branchname}, '', '', '');
1018 }
1019
1020 1;