Bug 28320: Add DB connection check to the SIP SC status message
[koha.git] / t / db_dependent / Circulation / issue.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 => 47;
21 use DateTime::Duration;
22
23 use t::lib::Mocks;
24 use t::lib::TestBuilder;
25
26 use C4::Biblio;
27 use C4::Circulation;
28 use C4::Context;
29 use C4::Items;
30 use C4::Reserves;
31 use Koha::Checkouts;
32 use Koha::Database;
33 use Koha::DateUtils;
34 use Koha::Holds;
35 use Koha::Items;
36 use Koha::Library;
37 use Koha::Patrons;
38 use Koha::CirculationRules;
39 use Koha::Statistics;
40
41 BEGIN {
42     require_ok('C4::Circulation');
43 }
44
45 can_ok(
46     'C4::Circulation',
47     qw(AddIssue
48       AddIssuingCharge
49       AddRenewal
50       AddReturn
51       GetIssuingCharges
52       GetOpenIssue
53       GetRenewCount
54       GetUpcomingDueIssues
55       )
56 );
57
58 #Start transaction
59 my $schema = Koha::Database->schema;
60 $schema->storage->txn_begin;
61 my $dbh = C4::Context->dbh;
62
63 my $builder = t::lib::TestBuilder->new();
64
65 $dbh->do(q|DELETE FROM issues|);
66 $dbh->do(q|DELETE FROM items|);
67 $dbh->do(q|DELETE FROM borrowers|);
68 $dbh->do(q|DELETE FROM categories|);
69 $dbh->do(q|DELETE FROM accountlines|);
70 $dbh->do(q|DELETE FROM circulation_rules|);
71 $dbh->do(q|DELETE FROM reserves|);
72 $dbh->do(q|DELETE FROM old_reserves|);
73 $dbh->do(q|DELETE FROM statistics|);
74
75 # Generate sample datas
76 my $itemtype = $builder->build(
77     {   source => 'Itemtype',
78         value  => { notforloan => undef, rentalcharge => 0 }
79     }
80 )->{itemtype};
81 my $branchcode_1 = $builder->build({ source => 'Branch' })->{branchcode};
82 my $branchcode_2 = $builder->build({ source => 'Branch' })->{branchcode};
83 my $branchcode_3 = $builder->build({ source => 'Branch' })->{branchcode};
84 my $categorycode = $builder->build({
85         source => 'Category',
86         value => { enrolmentfee => undef }
87     })->{categorycode};
88
89 # A default issuingrule should always be present
90 Koha::CirculationRules->set_rules(
91     {
92         itemtype     => '*',
93         categorycode => '*',
94         branchcode   => '*',
95         rules        => {
96             lengthunit      => 'days',
97             issuelength     => 0,
98             renewalperiod   => 0,
99             renewalsallowed => 0
100         }
101     }
102 );
103
104 # Add Dates
105 my $dt_today = dt_from_string;
106 my $today    = output_pref(
107     {   dt         => $dt_today,
108         dateformat => 'iso',
109         timeformat => '24hr',
110         dateonly   => 1
111     }
112 );
113
114 my $dt_today2 = dt_from_string;
115 my $dur10 = DateTime::Duration->new( days => -10 );
116 $dt_today2->add_duration($dur10);
117 my $daysago10 = output_pref(
118     {   dt         => $dt_today2,
119         dateformat => 'iso',
120         timeformat => '24hr',
121         dateonly   => 1
122     }
123 );
124
125 # Add biblio and item
126 my $record = MARC::Record->new();
127 $record->append_fields(
128     MARC::Field->new( '952', '0', '0', a => $branchcode_1 ) );
129
130 my ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio( $record, '' );
131
132 my $barcode_1 = 'barcode_1';
133 my $barcode_2 = 'barcode_2';
134 my $item_id1 = Koha::Item->new(
135     {
136         biblionumber   => $biblionumber,
137         barcode        => $barcode_1,
138         itemcallnumber => 'callnumber1',
139         homebranch     => $branchcode_1,
140         holdingbranch  => $branchcode_1,
141         itype          => $itemtype
142     },
143 )->store->itemnumber;
144 my $item_id2 = Koha::Item->new(
145     {
146         biblionumber   => $biblionumber,
147         barcode        => $barcode_2,
148         itemcallnumber => 'callnumber2',
149         homebranch     => $branchcode_2,
150         holdingbranch  => $branchcode_2,
151         notforloan     => 1,
152         itype          => $itemtype
153     },
154 )->store->itemnumber;
155
156 #Add borrower
157 my $borrower_id1 = Koha::Patron->new({
158     firstname    => 'firstname1',
159     surname      => 'surname1 ',
160     categorycode => $categorycode,
161     branchcode   => $branchcode_1
162 })->store->borrowernumber;
163 my $patron_1 = Koha::Patrons->find( $borrower_id1 );
164 my $borrower_1 = $patron_1->unblessed;
165 my $borrower_id2 = Koha::Patron->new({
166     firstname    => 'firstname2',
167     surname      => 'surname2 ',
168     categorycode => $categorycode,
169     branchcode   => $branchcode_2,
170 })->store->borrowernumber;
171 my $patron_2 = Koha::Patrons->find( $borrower_id2 );
172 my $borrower_2 = $patron_2->unblessed;
173
174 t::lib::Mocks::mock_userenv({ patron => $patron_1 });
175
176 #Begin Tests
177
178 #Test AddIssue
179 my $query = " SELECT count(*) FROM issues";
180 my $sth = $dbh->prepare($query);
181 $sth->execute;
182 my $countissue = $sth -> fetchrow_array;
183 is ($countissue ,0, "there is no issue");
184 my $issue1 = C4::Circulation::AddIssue( $borrower_1, $barcode_1, $daysago10,0, $today, '' );
185 is( ref $issue1, 'Koha::Checkout',
186        'AddIssue returns a Koha::Checkout object' );
187 my $datedue1 = dt_from_string( $issue1->date_due() );
188 like(
189     $datedue1,
190     qr/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/,
191     "Koha::Checkout->date_due() returns a date"
192 );
193 my $issue_id1 = $issue1->issue_id;
194
195 my $issue2 = C4::Circulation::AddIssue( $borrower_1, 'nonexistent_barcode' );
196 is( $issue2, undef, "AddIssue returns undef if no datedue is specified" );
197
198 $sth->execute;
199 $countissue = $sth -> fetchrow_array;
200 is ($countissue,1,"1 issues have been added");
201
202 #Test AddIssuingCharge
203 $query = " SELECT count(*) FROM accountlines";
204 $sth = $dbh->prepare($query);
205 $sth->execute;
206 my $countaccount = $sth->fetchrow_array;
207 is ($countaccount,0,"0 accountline exists");
208 my $checkout = Koha::Checkouts->find( $issue_id1 );
209 my $charge = C4::Circulation::AddIssuingCharge( $checkout, 10, 'RENT' );
210 is( ref( $charge ), 'Koha::Account::Line', "An issuing charge has been added" );
211 is( $charge->issue_id, $issue_id1, 'Issue id is set correctly for issuing charge' );
212 my $offset = Koha::Account::Offsets->find( { debit_id => $charge->id } );
213 is( $offset->credit_id, undef, 'Offset was created');
214 $sth->execute;
215 $countaccount = $sth->fetchrow_array;
216 is ($countaccount,1,"1 accountline has been added");
217
218 # Test AddRenewal
219
220 my $se = Test::MockModule->new( 'C4::Context' );
221 $se->mock( 'interface', sub {return 'intranet'});
222
223 # Let's renew this one at a different library for statistical purposes to test Bug 17781
224 # Mocking userenv with a different branchcode
225 t::lib::Mocks::mock_userenv({ patron => $patron_2, branchcode => $branchcode_3 });
226
227 my $datedue3 = AddRenewal( $borrower_id1, $item_id1, $branchcode_1, $datedue1, $daysago10 );
228
229 # Restoring the userenv with the original branchcode
230 t::lib::Mocks::mock_userenv({ patron => $patron_1});
231
232 like(
233     $datedue3,
234     qr/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/,
235     "AddRenewal returns a date"
236 );
237
238 my $stat = $dbh->selectrow_hashref("SELECT * FROM statistics WHERE type = 'renew' AND borrowernumber = ? AND itemnumber = ? AND branch = ?", undef, $borrower_id1, $item_id1, $branchcode_3 );
239 ok( $stat, "Bug 17781 - 'Improper branchcode set during renewal' still fixed" );
240
241 subtest 'Show that AddRenewal respects OpacRenewalBranch and interface' => sub {
242     plan tests => 10;
243
244     my $item_library = $builder->build_object( { class => 'Koha::Libraries' } );
245     my $patron       = $builder->build_object( { class => 'Koha::Patrons' } );
246     my $logged_in_user = $builder->build_object( { class => 'Koha::Patrons' } );
247     t::lib::Mocks::mock_userenv( { patron => $logged_in_user } );
248
249     my $OpacRenewalBranch = {
250         opacrenew        => "OPACRenew",
251         checkoutbranch   => $logged_in_user->branchcode,
252         patronhomebranch => $patron->branchcode,
253         itemhomebranch   => $item_library->branchcode,
254         none             => "",
255     };
256
257     while ( my ( $syspref, $expected_branchcode ) = each %$OpacRenewalBranch ) {
258
259         t::lib::Mocks::mock_preference( 'OpacRenewalBranch', $syspref );
260
261         {
262             $se->mock( 'interface', sub { return 'opac' } );
263
264             my $item = $builder->build_sample_item(
265                 { library => $item_library->branchcode, itype => $itemtype } );
266             my $opac_renew_issue =
267               C4::Circulation::AddIssue( $patron->unblessed, $item->barcode );
268
269             AddRenewal( $patron->borrowernumber, $item->itemnumber,
270                 "Stavromula", $datedue1, $daysago10 );
271
272             my $stat = Koha::Statistics->search(
273                 { itemnumber => $item->itemnumber, type => 'renew' } )->next;
274             is( $stat->branch, $expected_branchcode,
275                 "->renewal_branchcode is respected for OpacRenewalBranch = $syspref"
276             );
277         }
278
279         {
280             $se->mock( 'interface', sub { return 'intranet' } );
281
282             my $item = $builder->build_sample_item(
283                 { library => $item_library->branchcode, itype => $itemtype } );
284             my $opac_renew_issue =
285               C4::Circulation::AddIssue( $patron->unblessed, $item->barcode );
286
287             AddRenewal( $patron->borrowernumber, $item->itemnumber,
288                 "Stavromula", $datedue1, $daysago10 );
289
290             my $stat = Koha::Statistics->search(
291                 { itemnumber => $item->itemnumber, type => 'renew' } )->next;
292             is( $stat->branch, $logged_in_user->branchcode,
293                 "->renewal_branchcode is always logged in branch for intranet"
294             );
295         }
296     }
297 };
298
299 #Test GetOpenIssue
300 is( GetOpenIssue(), undef, "Without parameter GetOpenIssue returns undef" );
301 is( GetOpenIssue(-1), undef,
302     "With wrong parameter GetOpenIssue returns undef" );
303 my $openissue = GetOpenIssue($borrower_id1, $item_id1);
304
305 my @renewcount;
306 #Test GetRenewCount
307 my $issue3 = C4::Circulation::AddIssue( $borrower_1, $barcode_1 );
308 #Without anything in DB
309 @renewcount = C4::Circulation::GetRenewCount();
310 is_deeply(
311     \@renewcount,
312     [ 0, 0, 0, 0, 0, 0 ], # FIXME Need to be fixed, see FIXME in GetRenewCount
313     "Without issuing rules and without parameter, GetRenewCount returns renewcount = 0, renewsallowed = undef, renewsleft = 0"
314 );
315 @renewcount = C4::Circulation::GetRenewCount(-1);
316 is_deeply(
317     \@renewcount,
318     [ 0, 0, 0, 0, 0, 0 ], # FIXME Need to be fixed
319     "Without issuing rules and without wrong parameter, GetRenewCount returns renewcount = 0, renewsallowed = undef, renewsleft = 0"
320 );
321 @renewcount = C4::Circulation::GetRenewCount($borrower_id1, $item_id1);
322 is_deeply(
323     \@renewcount,
324     [ 2, 0, 0, 0, 0, 0 ],
325     "Without issuing rules and with a valid parameter, renewcount = 2, renewsallowed = undef, renewsleft = 0"
326 );
327
328 #With something in DB
329 @renewcount = C4::Circulation::GetRenewCount();
330 is_deeply(
331     \@renewcount,
332     [ 0, 0, 0, 0, 0, 0 ],
333     "With issuing rules (renewal disallowed) and without parameter, GetRenewCount returns renewcount = 0, renewsallowed = 0, renewsleft = 0"
334 );
335 @renewcount = C4::Circulation::GetRenewCount(-1);
336 is_deeply(
337     \@renewcount,
338     [ 0, 0, 0, 0, 0, 0 ],
339     "With issuing rules (renewal disallowed) and without wrong parameter, GetRenewCount returns renewcount = 0, renewsallowed = 0, renewsleft = 0"
340 );
341 @renewcount = C4::Circulation::GetRenewCount($borrower_id1, $item_id1);
342 is_deeply(
343     \@renewcount,
344     [ 2, 0, 0, 0, 0, 0 ],
345     "With issuing rules (renewal disallowed) and with a valid parameter, Getrenewcount returns renewcount = 2, renewsallowed = 0, renewsleft = 0"
346 );
347
348 # Add a default rule: renewal is allowed
349 Koha::CirculationRules->set_rules(
350     {
351         categorycode => undef,
352         itemtype     => undef,
353         branchcode   => undef,
354         rules        => {
355             renewalsallowed => 3,
356         }
357     }
358 );
359 @renewcount = C4::Circulation::GetRenewCount($borrower_id1, $item_id1);
360 is_deeply(
361     \@renewcount,
362     [ 2, 3, 1, 0, 0, 0 ],
363     "With issuing rules (renewal allowed) and with a valid parameter, Getrenewcount of item1 returns 3 renews left"
364 );
365
366 AddRenewal( $borrower_id1, $item_id1, $branchcode_1,
367     $datedue3, $daysago10 );
368 @renewcount = C4::Circulation::GetRenewCount($borrower_id1, $item_id1);
369 is_deeply(
370     \@renewcount,
371     [ 3, 3, 0, 0, 0, 0 ],
372     "With issuing rules (renewal allowed, 1 remaining) and with a valid parameter, Getrenewcount of item1 returns 0 renews left"
373 );
374
375 $dbh->do("DELETE FROM old_issues");
376 AddReturn($barcode_1);
377 my $return = $dbh->selectrow_hashref("SELECT DATE(returndate) AS return_date, CURRENT_DATE() AS today FROM old_issues LIMIT 1" );
378 ok( $return->{return_date} eq $return->{today}, "Item returned with no return date specified has todays date" );
379
380 $dbh->do("DELETE FROM old_issues");
381 C4::Circulation::AddIssue( $borrower_1, $barcode_1, $daysago10, 0, $today );
382 AddReturn($barcode_1, undef, undef, dt_from_string('2014-04-01 23:42'));
383 $return = $dbh->selectrow_hashref("SELECT * FROM old_issues LIMIT 1" );
384 ok( $return->{returndate} eq '2014-04-01 23:42:00', "Item returned with a return date of '2014-04-01 23:42' has that return date" );
385
386 my $itemnumber = Koha::Item->new(
387     {
388         biblionumber   => $biblionumber,
389         barcode        => 'barcode_3',
390         itemcallnumber => 'callnumber3',
391         homebranch     => $branchcode_1,
392         holdingbranch  => $branchcode_1,
393         notforloan     => 1,
394         itype          => $itemtype
395     },
396 )->store->itemnumber;
397
398 t::lib::Mocks::mock_preference( 'UpdateNotForLoanStatusOnCheckin', q{} );
399 AddReturn( 'barcode_3', $branchcode_1 );
400 my $item = Koha::Items->find( $itemnumber );
401 ok( $item->notforloan eq 1, 'UpdateNotForLoanStatusOnCheckin does not modify value when not enabled' );
402
403 t::lib::Mocks::mock_preference( 'UpdateNotForLoanStatusOnCheckin', '1: 9' );
404 AddReturn( 'barcode_3', $branchcode_1 );
405 $item = Koha::Items->find( $itemnumber );
406 ok( $item->notforloan eq 9, q{UpdateNotForLoanStatusOnCheckin updates notforloan value from 1 to 9 with setting "1: 9"} );
407
408 AddReturn( 'barcode_3', $branchcode_1 );
409 $item = Koha::Items->find( $itemnumber );
410 ok( $item->notforloan eq 9, q{UpdateNotForLoanStatusOnCheckin does not update notforloan value from 9 with setting "1: 9"} );
411
412 my $itemnumber2 = Koha::Item->new(
413     {
414         biblionumber   => $biblionumber,
415         barcode        => 'barcode_4',
416         itemcallnumber => 'callnumber4',
417         homebranch     => $branchcode_1,
418         holdingbranch  => $branchcode_1,
419         location       => 'FIC',
420         itype          => $itemtype
421     }
422 )->store->itemnumber;
423
424 t::lib::Mocks::mock_preference( 'UpdateItemLocationOnCheckin', q{} );
425 AddReturn( 'barcode_4', $branchcode_1 );
426 my $item2 = Koha::Items->find( $itemnumber2 );
427 ok( $item2->location eq 'FIC', 'UpdateItemLocationOnCheckin does not modify value when not enabled' );
428
429 t::lib::Mocks::mock_preference( 'UpdateItemLocationOnCheckin', 'FIC: GEN' );
430 AddReturn( 'barcode_4', $branchcode_1 );
431 $item2 = Koha::Items->find( $itemnumber2 );
432 is( $item2->location, 'GEN', q{UpdateItemLocationOnCheckin updates location value from 'FIC' to 'GEN' with setting "FIC: GEN"} );
433 is( $item2->permanent_location, 'GEN', q{UpdateItemLocationOnCheckin updates permanent_location value from 'FIC' to 'GEN' with setting "FIC: GEN"} );
434 AddReturn( 'barcode_4', $branchcode_1 );
435 $item2 = Koha::Items->find( $itemnumber2 );
436 ok( $item2->location eq 'GEN', q{UpdateItemLocationOnCheckin does not update location value from 'GEN' with setting "FIC: GEN"} );
437
438 t::lib::Mocks::mock_preference( 'UpdateItemLocationOnCheckin', '_ALL_: CART' );
439 AddReturn( 'barcode_4', $branchcode_1 );
440 $item2 = Koha::Items->find( $itemnumber2 );
441 ok( $item2->location eq 'CART', q{UpdateItemLocationOnCheckin updates location value from 'GEN' with setting "_ALL_: CART"} );
442 Koha::Item::Transfer->new({
443     itemnumber => $itemnumber2,
444     frombranch => $branchcode_2,
445     tobranch => $branchcode_1,
446     datesent => '2020-01-01'
447 })->store;
448 AddReturn( 'barcode_4', $branchcode_1 );
449 $item2 = Koha::Items->find( $itemnumber2 );
450 ok( $item2->location eq 'CART', q{UpdateItemLocationOnCheckin updates location value from 'GEN' with setting "_ALL_: CART" when transfer filled} );
451
452 ok( $item2->permanent_location eq 'GEN', q{UpdateItemLocationOnCheckin does not update permanent_location value from 'GEN' with setting "_ALL_: CART"} );
453 AddIssue( $borrower_1, 'barcode_4', $daysago10,0, $today, '' );
454 $item2 = Koha::Items->find( $itemnumber2 );
455 ok( $item2->location eq 'GEN', q{Location updates from 'CART' to permanent location on issue} );
456
457 t::lib::Mocks::mock_preference( 'UpdateItemLocationOnCheckin', "GEN: _BLANK_\n_BLANK_: PROC\nPROC: _PERM_" );
458 AddReturn( 'barcode_4', $branchcode_1 );
459 $item2 = Koha::Items->find( $itemnumber2 );
460 ok( $item2->location eq '', q{UpdateItemLocationOnCheckin updates location value from 'GEN' to '' with setting "GEN: _BLANK_"} );
461 AddReturn( 'barcode_4', $branchcode_1 );
462 $item2 = Koha::Items->find( $itemnumber2 );
463 ok( $item2->location eq 'PROC' , q{UpdateItemLocationOnCheckin updates location value from '' to 'PROC' with setting "_BLANK_: PROC"} );
464 ok( $item2->permanent_location eq '' , q{UpdateItemLocationOnCheckin does not update permanent_location value from '' to 'PROC' with setting "_BLANK_: PROC"} );
465 AddReturn( 'barcode_4', $branchcode_1 );
466 $item2 = Koha::Items->find( $itemnumber2 );
467 ok( $item2->location eq '' , q{UpdateItemLocationOnCheckin updates location value from 'PROC' to '' with setting "PROC: _PERM_" } );
468 ok( $item2->permanent_location eq '' , q{UpdateItemLocationOnCheckin does not update permanent_location from '' with setting "PROC: _PERM_" } );
469
470
471
472
473 # Bug 14640 - Cancel the hold on checking out if asked
474 my $reserve_id = AddReserve(
475     {
476         branchcode     => $branchcode_1,
477         borrowernumber => $borrower_id1,
478         biblionumber   => $biblionumber,
479         priority       => 1,
480         notes          => "a note",
481         title          => "a title",
482     }
483 );
484 ok( $reserve_id, 'The reserve should have been inserted' );
485 AddIssue( $borrower_2, $barcode_1, dt_from_string, 'cancel' );
486 my $hold = Koha::Holds->find( $reserve_id );
487 is( $hold, undef, 'The reserve should have been correctly cancelled' );
488
489 # Unseen rewnewals
490 t::lib::Mocks::mock_preference('UnseenRenewals', 1);
491 # Add a default circ rule: 3 unseen renewals allowed
492 Koha::CirculationRules->set_rules(
493     {
494         categorycode => undef,
495         itemtype     => undef,
496         branchcode   => undef,
497         rules        => {
498             renewalsallowed => 10,
499             unseen_renewals_allowed => 3
500         }
501     }
502 );
503
504 my $unseen_library = $builder->build_object( { class => 'Koha::Libraries' } );
505 my $unseen_patron  = $builder->build_object( { class => 'Koha::Patrons' } );
506 my $unseen_item = $builder->build_sample_item(
507     { library => $unseen_library->branchcode, itype => $itemtype } );
508 my $unseen_issue = C4::Circulation::AddIssue( $unseen_patron->unblessed, $unseen_item->barcode );
509
510 # Does an unseen renewal increment the issue's count
511 my ( $unseen_before ) = ( C4::Circulation::GetRenewCount( $unseen_patron->borrowernumber, $unseen_item->itemnumber ) )[3];
512 AddRenewal( $unseen_patron->borrowernumber, $unseen_item->itemnumber, $branchcode_1, undef, undef, undef, 0 );
513 my ( $unseen_after ) = ( C4::Circulation::GetRenewCount( $unseen_patron->borrowernumber, $unseen_item->itemnumber ) )[3];
514 is( $unseen_after, $unseen_before + 1, 'unseen_renewals increments' );
515
516 # Does a seen renewal reset the unseen count
517 AddRenewal( $unseen_patron->borrowernumber, $unseen_item->itemnumber, $branchcode_1, undef, undef, undef, 1 );
518 my ( $unseen_reset ) = ( C4::Circulation::GetRenewCount( $unseen_patron->borrowernumber, $unseen_item->itemnumber ) )[3];
519 is( $unseen_reset, 0, 'seen renewal resets the unseen count' );
520
521 #End transaction
522 $schema->storage->txn_rollback;