Bug 13113 [QA Followup] - Fix 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 C4::Biblio;
22 use C4::Branch;
23 use C4::Items;
24 use C4::Members;
25 use C4::Reserves;
26 use Koha::DateUtils;
27 use Koha::Database;
28
29 use Test::More tests => 55;
30
31 BEGIN {
32     use_ok('C4::Circulation');
33 }
34
35 my $dbh = C4::Context->dbh;
36 my $schema = Koha::Database->new()->schema();
37
38 # Start transaction
39 $dbh->{AutoCommit} = 0;
40 $dbh->{RaiseError} = 1;
41
42 # Start with a clean slate
43 $dbh->do('DELETE FROM issues');
44
45 my $CircControl = C4::Context->preference('CircControl');
46 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
47
48 my $item = {
49     homebranch => 'MPL',
50     holdingbranch => 'MPL'
51 };
52
53 my $borrower = {
54     branchcode => 'MPL'
55 };
56
57 # No userenv, PickupLibrary
58 C4::Context->set_preference('CircControl', 'PickupLibrary');
59 is(
60     C4::Context->preference('CircControl'),
61     'PickupLibrary',
62     'CircControl changed to PickupLibrary'
63 );
64 is(
65     C4::Circulation::_GetCircControlBranch($item, $borrower),
66     $item->{$HomeOrHoldingBranch},
67     '_GetCircControlBranch returned item branch (no userenv defined)'
68 );
69
70 # No userenv, PatronLibrary
71 C4::Context->set_preference('CircControl', 'PatronLibrary');
72 is(
73     C4::Context->preference('CircControl'),
74     'PatronLibrary',
75     'CircControl changed to PatronLibrary'
76 );
77 is(
78     C4::Circulation::_GetCircControlBranch($item, $borrower),
79     $borrower->{branchcode},
80     '_GetCircControlBranch returned borrower branch'
81 );
82
83 # No userenv, ItemHomeLibrary
84 C4::Context->set_preference('CircControl', 'ItemHomeLibrary');
85 is(
86     C4::Context->preference('CircControl'),
87     'ItemHomeLibrary',
88     'CircControl changed to ItemHomeLibrary'
89 );
90 is(
91     $item->{$HomeOrHoldingBranch},
92     C4::Circulation::_GetCircControlBranch($item, $borrower),
93     '_GetCircControlBranch returned item branch'
94 );
95
96 # Now, set a userenv
97 C4::Context->_new_userenv('xxx');
98 C4::Context::set_userenv(0,0,0,'firstname','surname', 'MPL', 'Midway Public Library', '', '', '');
99 is(C4::Context->userenv->{branch}, 'MPL', 'userenv set');
100
101 # Userenv set, PickupLibrary
102 C4::Context->set_preference('CircControl', 'PickupLibrary');
103 is(
104     C4::Context->preference('CircControl'),
105     'PickupLibrary',
106     'CircControl changed to PickupLibrary'
107 );
108 is(
109     C4::Circulation::_GetCircControlBranch($item, $borrower),
110     'MPL',
111     '_GetCircControlBranch returned current branch'
112 );
113
114 # Userenv set, PatronLibrary
115 C4::Context->set_preference('CircControl', 'PatronLibrary');
116 is(
117     C4::Context->preference('CircControl'),
118     'PatronLibrary',
119     'CircControl changed to PatronLibrary'
120 );
121 is(
122     C4::Circulation::_GetCircControlBranch($item, $borrower),
123     $borrower->{branchcode},
124     '_GetCircControlBranch returned borrower branch'
125 );
126
127 # Userenv set, ItemHomeLibrary
128 C4::Context->set_preference('CircControl', 'ItemHomeLibrary');
129 is(
130     C4::Context->preference('CircControl'),
131     'ItemHomeLibrary',
132     'CircControl changed to ItemHomeLibrary'
133 );
134 is(
135     C4::Circulation::_GetCircControlBranch($item, $borrower),
136     $item->{$HomeOrHoldingBranch},
137     '_GetCircControlBranch returned item branch'
138 );
139
140 # Reset initial configuration
141 C4::Context->set_preference('CircControl', $CircControl);
142 is(
143     C4::Context->preference('CircControl'),
144     $CircControl,
145     'CircControl reset to its initial value'
146 );
147
148 # Set a simple circ policy
149 $dbh->do('DELETE FROM issuingrules');
150 $dbh->do(
151     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
152                                 maxissueqty, issuelength, lengthunit,
153                                 renewalsallowed, renewalperiod,
154                                 norenewalbefore, auto_renew,
155                                 fine, chargeperiod)
156       VALUES (?, ?, ?, ?,
157               ?, ?, ?,
158               ?, ?,
159               ?, ?,
160               ?, ?
161              )
162     },
163     {},
164     '*', '*', '*', 25,
165     20, 14, 'days',
166     1, 7,
167     '', 0,
168     .10, 1
169 );
170
171 # Test C4::Circulation::ProcessOfflinePayment
172 my $sth = C4::Context->dbh->prepare("SELECT COUNT(*) FROM accountlines WHERE amount = '-123.45' AND accounttype = 'Pay'");
173 $sth->execute();
174 my ( $original_count ) = $sth->fetchrow_array();
175
176 C4::Context->dbh->do("INSERT INTO borrowers ( cardnumber, surname, firstname, categorycode, branchcode ) VALUES ( '99999999999', 'Hall', 'Kyle', 'S', 'MPL' )");
177
178 C4::Circulation::ProcessOfflinePayment({ cardnumber => '99999999999', amount => '123.45' });
179
180 $sth->execute();
181 my ( $new_count ) = $sth->fetchrow_array();
182
183 ok( $new_count == $original_count  + 1, 'ProcessOfflinePayment makes payment correctly' );
184
185 C4::Context->dbh->do("DELETE FROM accountlines WHERE borrowernumber IN ( SELECT borrowernumber FROM borrowers WHERE cardnumber = '99999999999' )");
186 C4::Context->dbh->do("DELETE FROM borrowers WHERE cardnumber = '99999999999'");
187 C4::Context->dbh->do("DELETE FROM accountlines");
188 {
189 # CanBookBeRenewed tests
190
191     # Generate test biblio
192     my $biblio = MARC::Record->new();
193     my $title = 'Silence in the library';
194     $biblio->append_fields(
195         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
196         MARC::Field->new('245', ' ', ' ', a => $title),
197     );
198
199     my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, '');
200
201     my $barcode = 'R00000342';
202     my $branch = 'MPL';
203
204     my ( $item_bibnum, $item_bibitemnum, $itemnumber ) = AddItem(
205         {
206             homebranch       => $branch,
207             holdingbranch    => $branch,
208             barcode          => $barcode,
209             replacementprice => 12.00
210         },
211         $biblionumber
212     );
213
214     my $barcode2 = 'R00000343';
215     my ( $item_bibnum2, $item_bibitemnum2, $itemnumber2 ) = AddItem(
216         {
217             homebranch       => $branch,
218             holdingbranch    => $branch,
219             barcode          => $barcode2,
220             replacementprice => 23.00
221         },
222         $biblionumber
223     );
224
225     my $barcode3 = 'R00000346';
226     my ( $item_bibnum3, $item_bibitemnum3, $itemnumber3 ) = AddItem(
227         {
228             homebranch       => $branch,
229             holdingbranch    => $branch,
230             barcode          => $barcode3,
231             replacementprice => 23.00
232         },
233         $biblionumber
234     );
235
236     # Create 2 borrowers
237     my %renewing_borrower_data = (
238         firstname =>  'John',
239         surname => 'Renewal',
240         categorycode => 'S',
241         branchcode => $branch,
242     );
243
244     my %reserving_borrower_data = (
245         firstname =>  'Katrin',
246         surname => 'Reservation',
247         categorycode => 'S',
248         branchcode => $branch,
249     );
250
251     my $renewing_borrowernumber = AddMember(%renewing_borrower_data);
252     my $reserving_borrowernumber = AddMember(%reserving_borrower_data);
253
254     my $renewing_borrower = GetMember( borrowernumber => $renewing_borrowernumber );
255
256     my $constraint     = 'a';
257     my $bibitems       = '';
258     my $priority       = '1';
259     my $resdate        = undef;
260     my $expdate        = undef;
261     my $notes          = '';
262     my $checkitem      = undef;
263     my $found          = undef;
264
265     my $datedue = AddIssue( $renewing_borrower, $barcode);
266     is (defined $datedue, 1, "Item 1 checked out, due date: $datedue");
267
268     my $datedue2 = AddIssue( $renewing_borrower, $barcode2);
269     is (defined $datedue2, 1, "Item 2 checked out, due date: $datedue2");
270
271     my $borrowing_borrowernumber = GetItemIssue($itemnumber)->{borrowernumber};
272     is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
273
274     my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber, 1);
275     is( $renewokay, 1, 'Can renew, no holds for this title or item');
276
277
278     # Biblio-level hold, renewal test
279     AddReserve(
280         $branch, $reserving_borrowernumber, $biblionumber,
281         $constraint, $bibitems,  $priority, $resdate, $expdate, $notes,
282         $title, $checkitem, $found
283     );
284
285     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
286     is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
287     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
288
289     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2);
290     is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
291     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
292
293     my $reserveid = C4::Reserves::GetReserveId({ biblionumber => $biblionumber, borrowernumber => $reserving_borrowernumber});
294     my $reserving_borrower = GetMember( borrowernumber => $reserving_borrowernumber );
295     AddIssue($reserving_borrower, $barcode3);
296     my $reserve = $dbh->selectrow_hashref(
297         'SELECT * FROM old_reserves WHERE reserve_id = ?',
298         { Slice => {} },
299         $reserveid
300     );
301     is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
302
303     # Item-level hold, renewal test
304     AddReserve(
305         $branch, $reserving_borrowernumber, $biblionumber,
306         $constraint, $bibitems,  $priority, $resdate, $expdate, $notes,
307         $title, $itemnumber, $found
308     );
309
310     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber, 1);
311     is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
312     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
313
314     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber2, 1);
315     is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
316
317
318     # Items can't fill hold for reasons
319     ModItem({ notforloan => 1 }, $biblionumber, $itemnumber);
320     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber, 1);
321     is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
322     ModItem({ notforloan => 0, itype => '' }, $biblionumber, $itemnumber,1);
323
324     # FIXME: Add more for itemtype not for loan etc.
325
326     $reserveid = C4::Reserves::GetReserveId({ biblionumber => $biblionumber, itemnumber => $itemnumber, borrowernumber => $reserving_borrowernumber});
327     CancelReserve({ reserve_id => $reserveid });
328
329     # Test automatic renewal before value for "norenewalbefore" in policy is set
330     my $barcode4 = '11235813';
331     my ( $item_bibnum4, $item_bibitemnum4, $itemnumber4 ) = AddItem(
332         {
333             homebranch       => $branch,
334             holdingbranch    => $branch,
335             barcode          => $barcode4,
336             replacementprice => 16.00
337         },
338         $biblionumber
339     );
340
341     AddIssue( $renewing_borrower, $barcode4, undef, undef, undef, undef, { auto_renew => 1 } );
342     ( $renewokay, $error ) =
343       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
344     is( $renewokay, 0, 'Cannot renew, renewal is automatic' );
345     is( $error, 'auto_renew',
346         'Cannot renew, renewal is automatic (returned code is auto_renew)' );
347
348     # set policy to require that loans cannot be
349     # renewed until seven days prior to the due date
350     $dbh->do('UPDATE issuingrules SET norenewalbefore = 7');
351     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
352     is( $renewokay, 0, 'Cannot renew, renewal is premature');
353     is( $error, 'too_soon', 'Cannot renew, renewal is premature (returned code is too_soon)');
354     is(
355         GetSoonestRenewDate($renewing_borrowernumber, $itemnumber),
356         $datedue->clone->add(days => -7),
357         'renewals permitted 7 days before due date, as expected',
358     );
359
360     # Test automatic renewal again
361     ( $renewokay, $error ) =
362       CanBookBeRenewed( $renewing_borrowernumber, $itemnumber4 );
363     is( $renewokay, 0, 'Cannot renew, renewal is automatic and premature' );
364     is( $error, 'auto_too_soon',
365 'Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
366     );
367
368     # Too many renewals
369
370     # set policy to forbid renewals
371     $dbh->do('UPDATE issuingrules SET norenewalbefore = NULL, renewalsallowed = 0');
372
373     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $itemnumber);
374     is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
375     is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
376
377     # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
378     C4::Context->set_preference('WhenLostForgiveFine','1');
379     C4::Context->set_preference('WhenLostChargeReplacementFee','1');
380
381     C4::Overdues::UpdateFine( $itemnumber, $renewing_borrower->{borrowernumber},
382         15.00, q{}, Koha::DateUtils::output_pref($datedue) );
383
384     LostItem( $itemnumber, 1 );
385
386     my $item = $schema->resultset('Item')->find( $itemnumber );
387     ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
388
389     my $total_due = $dbh->selectrow_array(
390         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
391         undef, $renewing_borrower->{borrowernumber}
392     );
393
394     ok( $total_due == 12, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
395
396     C4::Context->dbh->do("DELETE FROM accountlines");
397
398     C4::Context->set_preference('WhenLostForgiveFine','0');
399     C4::Context->set_preference('WhenLostChargeReplacementFee','0');
400
401     C4::Overdues::UpdateFine( $itemnumber2, $renewing_borrower->{borrowernumber},
402         15.00, q{}, Koha::DateUtils::output_pref($datedue) );
403
404     LostItem( $itemnumber2, 0 );
405
406     my $item2 = $schema->resultset('Item')->find( $itemnumber2 );
407     ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
408
409     $total_due = $dbh->selectrow_array(
410         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
411         undef, $renewing_borrower->{borrowernumber}
412     );
413
414     ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
415
416     my $now = dt_from_string();
417     my $future = dt_from_string();
418     $future->add( days => 7 );
419     my $units = C4::Overdues::_get_chargeable_units('days', $future, $now, 'MPL');
420     ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
421 }
422
423 {
424     # GetUpcomingDueIssues tests
425     my $barcode  = 'R00000342';
426     my $barcode2 = 'R00000343';
427     my $barcode3 = 'R00000344';
428     my $branch   = 'MPL';
429
430     #Create another record
431     my $biblio2 = MARC::Record->new();
432     my $title2 = 'Something is worng here';
433     $biblio2->append_fields(
434         MARC::Field->new('100', ' ', ' ', a => 'Anonymous'),
435         MARC::Field->new('245', ' ', ' ', a => $title2),
436     );
437     my ($biblionumber2, $biblioitemnumber2) = AddBiblio($biblio2, '');
438
439     #Create third item
440     AddItem(
441         {
442             homebranch       => $branch,
443             holdingbranch    => $branch,
444             barcode          => $barcode3
445         },
446         $biblionumber2
447     );
448
449     # Create a borrower
450     my %a_borrower_data = (
451         firstname =>  'Fridolyn',
452         surname => 'SOMERS',
453         categorycode => 'S',
454         branchcode => $branch,
455     );
456
457     my $a_borrower_borrowernumber = AddMember(%a_borrower_data);
458     my $a_borrower = GetMember( borrowernumber => $a_borrower_borrowernumber );
459
460     my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
461     my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
462     my $today = DateTime->today(time_zone => C4::Context->tz());
463
464     my $datedue  = AddIssue( $a_borrower, $barcode, $yesterday );
465     my $datedue2 = AddIssue( $a_borrower, $barcode2, $two_days_ahead );
466
467     my $upcoming_dues;
468
469     # GetUpcomingDueIssues tests
470     for my $i(0..1) {
471         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
472         is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
473     }
474
475     #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
476     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
477     is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
478
479     for my $i(3..5) {
480         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
481         is ( scalar( @$upcoming_dues ), 1,
482             "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
483     }
484
485     # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
486
487     my $datedue3 = AddIssue( $a_borrower, $barcode3, $today );
488
489     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
490     is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
491
492     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
493     is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
494
495     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
496     is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
497
498     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 }  );
499     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
500
501     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
502     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
503
504     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
505     is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
506
507 }
508
509 $dbh->rollback;
510
511 1;