Bug 16492: Test that no_set_userenv will not set userenv if not exist yet
[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 Koha::DateUtils;
21 use DateTime::Duration;
22 use t::lib::Mocks;
23 use C4::Biblio;
24 use C4::Members;
25 use C4::Branch;
26 use C4::Circulation;
27 use C4::Items;
28 use C4::Context;
29 use C4::Reserves;
30
31 use Test::More tests => 32;
32
33 BEGIN {
34     use_ok('C4::Circulation');
35 }
36 can_ok(
37     'C4::Circulation',
38     qw(AddIssue
39       AddIssuingCharge
40       AddRenewal
41       AddReturn
42       GetBiblioIssues
43       GetIssuingCharges
44       GetIssuingRule
45       GetItemIssue
46       GetItemIssues
47       GetOpenIssue
48       GetRenewCount
49       GetUpcomingDueIssues
50       )
51 );
52
53 #Start transaction
54 my $dbh = C4::Context->dbh;
55 $dbh->{RaiseError} = 1;
56 $dbh->{AutoCommit} = 0;
57
58 $dbh->do(q|DELETE FROM issues|);
59 $dbh->do(q|DELETE FROM items|);
60 $dbh->do(q|DELETE FROM borrowers|);
61 $dbh->do(q|DELETE FROM branches|);
62 $dbh->do(q|DELETE FROM categories|);
63 $dbh->do(q|DELETE FROM accountlines|);
64 $dbh->do(q|DELETE FROM issuingrules|);
65
66 #Add sample datas
67
68 #Add Dates
69
70 my $dt_today    = dt_from_string;
71 my $today       = output_pref({ dt => $dt_today, dateformat => 'iso', timeformat => '24hr', dateonly => 1 });
72
73 my $dt_today2 = dt_from_string;
74 my $dur10 = DateTime::Duration->new( days => -10 );
75 $dt_today2->add_duration($dur10);
76 my $daysago10 = output_pref({ dt => $dt_today2, dateformat => 'iso', timeformat => '24hr', dateonly => 1 });
77
78 #Add branch and category
79 my $samplebranch1 = {
80     add            => 1,
81     branchcode     => 'CPL',
82     branchname     => 'Sample Branch',
83     branchaddress1 => 'sample adr1',
84     branchaddress2 => 'sample adr2',
85     branchaddress3 => 'sample adr3',
86     branchzip      => 'sample zip',
87     branchcity     => 'sample city',
88     branchstate    => 'sample state',
89     branchcountry  => 'sample country',
90     branchphone    => 'sample phone',
91     branchfax      => 'sample fax',
92     branchemail    => 'sample email',
93     branchurl      => 'sample url',
94     branchip       => 'sample ip',
95     branchprinter  => undef,
96     opac_info      => 'sample opac',
97 };
98 my $samplebranch2 = {
99     add            => 1,
100     branchcode     => 'MPL',
101     branchname     => 'Sample Branch2',
102     branchaddress1 => 'sample adr1_2',
103     branchaddress2 => 'sample adr2_2',
104     branchaddress3 => 'sample adr3_2',
105     branchzip      => 'sample zip2',
106     branchcity     => 'sample city2',
107     branchstate    => 'sample state2',
108     branchcountry  => 'sample country2',
109     branchphone    => 'sample phone2',
110     branchfax      => 'sample fax2',
111     branchemail    => 'sample email2',
112     branchurl      => 'sample url2',
113     branchip       => 'sample ip2',
114     branchprinter  => undef,
115     opac_info      => 'sample opac2',
116 };
117 ModBranch($samplebranch1);
118 ModBranch($samplebranch2);
119
120 my $samplecat = {
121     categorycode          => 'CAT1',
122     description           => 'Description1',
123     enrolmentperiod       => 'Null',
124     enrolmentperioddate   => 'Null',
125     dateofbirthrequired   => 'Null',
126     finetype              => 'Null',
127     bulk                  => 'Null',
128     enrolmentfee          => 'Null',
129     overduenoticerequired => 'Null',
130     issuelimit            => 'Null',
131     reservefee            => 'Null',
132     hidelostitems         => 0,
133     category_type         => 'Null'
134 };
135 my $query =
136 "INSERT INTO categories (categorycode,description,enrolmentperiod,enrolmentperioddate,dateofbirthrequired ,finetype,bulk,enrolmentfee,overduenoticerequired,issuelimit ,reservefee ,hidelostitems ,category_type) VALUES( ?,?,?,?,?,?,?,?,?,?,?,?,?)";
137 $dbh->do(
138     $query, {},
139     $samplecat->{categorycode},          $samplecat->{description},
140     $samplecat->{enrolmentperiod},       $samplecat->{enrolmentperioddate},
141     $samplecat->{dateofbirthrequired},   $samplecat->{finetype},
142     $samplecat->{bulk},                  $samplecat->{enrolmentfee},
143     $samplecat->{overduenoticerequired}, $samplecat->{issuelimit},
144     $samplecat->{reservefee},            $samplecat->{hidelostitems},
145     $samplecat->{category_type}
146 );
147
148 #Add biblio and item
149 my $record = MARC::Record->new();
150 $record->append_fields(
151     MARC::Field->new( '952', '0', '0', a => $samplebranch1->{branchcode} ) );
152 my ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio( $record, '' );
153
154 my $barcode_1 = 'barcode_1';
155 my $barcode_2 = 'barcode_2';
156 my @sampleitem1 = C4::Items::AddItem(
157     {
158         barcode        => $barcode_1,
159         itemcallnumber => 'callnumber1',
160         homebranch     => $samplebranch1->{branchcode},
161         holdingbranch  => $samplebranch1->{branchcode},
162         issue          => 1,
163         reserve        => 1
164     },
165     $biblionumber
166 );
167 my $item_id1    = $sampleitem1[2];
168 my @sampleitem2 = C4::Items::AddItem(
169     {
170         barcode        => $barcode_2,
171         itemcallnumber => 'callnumber2',
172         homebranch     => $samplebranch2->{branchcode},
173         holdingbranch  => $samplebranch2->{branchcode},
174         notforloan     => 1,
175         issue          => 1
176     },
177     $biblionumber
178 );
179 my $item_id2 = $sampleitem2[2];
180
181 #Add borrower
182 my $borrower_id1 = C4::Members::AddMember(
183     firstname    => 'firstname1',
184     surname      => 'surname1 ',
185     categorycode => $samplecat->{categorycode},
186     branchcode   => $samplebranch1->{branchcode},
187 );
188 my $borrower_1 = C4::Members::GetMember(borrowernumber => $borrower_id1);
189 my $borrower_id2 = C4::Members::AddMember(
190     firstname    => 'firstname2',
191     surname      => 'surname2 ',
192     categorycode => $samplecat->{categorycode},
193     branchcode   => $samplebranch2->{branchcode},
194 );
195 my $borrower_2 = C4::Members::GetMember(borrowernumber => $borrower_id2);
196
197 # NEED TO BE FIXED !!!
198 # The first parameter for set_userenv is the class ref
199 #my @USERENV = ( $borrower_id1, 'test', 'MASTERTEST', 'firstname', 'username', 'CPL', 'CPL', 'email@example.org' );
200 my @USERENV = ( $borrower_id1, 'test', 'MASTERTEST', 'firstname', 'CPL', 'CPL', 'email@example.org' );
201
202 C4::Context->_new_userenv('DUMMY_SESSION_ID');
203 C4::Context->set_userenv(@USERENV);
204
205 my $userenv = C4::Context->userenv
206   or BAIL_OUT("No userenv");
207
208 #Begin Tests
209
210 #Test AddIssue
211 $query = " SELECT count(*) FROM issues";
212 my $sth = $dbh->prepare($query);
213 $sth->execute;
214 my $countissue = $sth -> fetchrow_array;
215 is ($countissue ,0, "there is no issue");
216 my $issue1 = C4::Circulation::AddIssue( $borrower_1, $barcode_1, $daysago10,0, $today, '' );
217 is( ref $issue1, 'Koha::Schema::Result::Issue',
218        'AddIssue returns a Koha::Schema::Result::Issue object' );
219 my $datedue1 = dt_from_string( $issue1->date_due() );
220 like(
221     $datedue1,
222     qr/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/,
223     "Koha::Schema::Result::Issue->date_due() returns a date"
224 );
225 my $issue_id1 = $dbh->last_insert_id( undef, undef, 'issues', undef );
226
227 my $issue2 = C4::Circulation::AddIssue( $borrower_1, 'nonexistent_barcode' );
228 is( $issue2, undef, "AddIssue returns undef if no datedue is specified" );
229 my $issue_id2 = $dbh->last_insert_id( undef, undef, 'issues', undef );
230
231 $sth->execute;
232 $countissue = $sth -> fetchrow_array;
233 is ($countissue,1,"1 issues have been added");
234
235 #Test AddIssuingCharge
236 $query = " SELECT count(*) FROM accountlines";
237 $sth = $dbh->prepare($query);
238 $sth->execute;
239 my $countaccount = $sth -> fetchrow_array;
240 is ($countaccount,0,"0 accountline exists");
241 is( C4::Circulation::AddIssuingCharge( $item_id1, $borrower_id1, 10 ),
242     1, "An issuing charge has been added" );
243 my $account_id = $dbh->last_insert_id( undef, undef, 'accountlines', undef );
244 $sth->execute;
245 $countaccount = $sth -> fetchrow_array;
246 is ($countaccount,1,"1 accountline has been added");
247
248 #Test AddRenewal
249 my $datedue3 =
250   AddRenewal( $borrower_id1, $item_id1, $samplebranch1->{branchcode},
251     $datedue1, $daysago10 );
252 like(
253     $datedue3,
254     qr/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/,
255     "AddRenewal returns a date"
256 );
257
258 #Test GetBiblioIssues
259 is( GetBiblioIssues(), undef, "GetBiblio Issues without parameters" );
260
261 #Test GetItemIssue
262 #FIXME : As the issues are not correctly added in the database, these tests don't work correctly
263 is(GetItemIssue,undef,"Without parameter GetItemIssue returns undef");
264 #is(GetItemIssue($item_id1),{},"Item1's issues");
265
266 #Test GetItemIssues
267 #FIXME: this routine currently doesn't work be
268 #is_deeply (GetItemIssues,{},"Without parameter, GetItemIssue returns all the issues");
269
270 #Test GetOpenIssue
271 is( GetOpenIssue(), undef, "Without parameter GetOpenIssue returns undef" );
272 is( GetOpenIssue(-1), undef,
273     "With wrong parameter GetOpenIssue returns undef" );
274 my $openissue = GetOpenIssue($borrower_id1, $item_id1);
275
276 my @renewcount;
277 #Test GetRenewCount
278 my $issue3 = C4::Circulation::AddIssue( $borrower_1, $barcode_1 );
279 #Without anything in DB
280 @renewcount = C4::Circulation::GetRenewCount();
281 is_deeply(
282     \@renewcount,
283     [ 0, undef, 0 ], # FIXME Need to be fixed
284     "Without issuing rules and without parameter, GetRenewCount returns renewcount = 0, renewsallowed = undef, renewsleft = 0"
285 );
286 @renewcount = C4::Circulation::GetRenewCount(-1);
287 is_deeply(
288     \@renewcount,
289     [ 0, undef, 0 ], # FIXME Need to be fixed
290     "Without issuing rules and without wrong parameter, GetRenewCount returns renewcount = 0, renewsallowed = undef, renewsleft = 0"
291 );
292 @renewcount = C4::Circulation::GetRenewCount($borrower_id1, $item_id1);
293 is_deeply(
294     \@renewcount,
295     [ 2, undef, 0 ],
296     "Without issuing rules and with a valid parameter, renewcount = 2, renewsallowed = undef, renewsleft = 0"
297 );
298
299 #With something in DB
300 # Add a default rule: No renewal allowed
301 $dbh->do(q|
302     INSERT INTO issuingrules( categorycode, itemtype, branchcode, issuelength, renewalsallowed )
303     VALUES ( '*', '*', '*', 10, 0 )
304 |);
305 @renewcount = C4::Circulation::GetRenewCount();
306 is_deeply(
307     \@renewcount,
308     [ 0, 0, 0 ],
309     "With issuing rules (renewal disallowed) and without parameter, GetRenewCount returns renewcount = 0, renewsallowed = 0, renewsleft = 0"
310 );
311 @renewcount = C4::Circulation::GetRenewCount(-1);
312 is_deeply(
313     \@renewcount,
314     [ 0, 0, 0 ],
315     "With issuing rules (renewal disallowed) and without wrong parameter, GetRenewCount returns renewcount = 0, renewsallowed = 0, renewsleft = 0"
316 );
317 @renewcount = C4::Circulation::GetRenewCount($borrower_id1, $item_id1);
318 is_deeply(
319     \@renewcount,
320     [ 2, 0, 0 ],
321     "With issuing rules (renewal disallowed) and with a valid parameter, Getrenewcount returns renewcount = 2, renewsallowed = 0, renewsleft = 0"
322 );
323
324 # Add a default rule: renewal is allowed
325 $dbh->do(q|
326     UPDATE issuingrules SET renewalsallowed = 3
327 |);
328 @renewcount = C4::Circulation::GetRenewCount();
329 is_deeply(
330     \@renewcount,
331     [ 0, 3, 3 ],
332     "With issuing rules (renewal allowed) and without parameter, GetRenewCount returns renewcount = 0, renewsallowed = 3, renewsleft = 3"
333 );
334 @renewcount = C4::Circulation::GetRenewCount(-1);
335 is_deeply(
336     \@renewcount,
337     [ 0, 3, 3 ],
338     "With issuing rules (renewal allowed) and without wrong parameter, GetRenewCount returns renewcount = 0, renewsallowed = 3, renewsleft = 3"
339 );
340 @renewcount = C4::Circulation::GetRenewCount($borrower_id1, $item_id1);
341 is_deeply(
342     \@renewcount,
343     [ 2, 3, 1 ],
344     "With issuing rules (renewal allowed) and with a valid parameter, Getrenewcount of item1 returns 3 renews left"
345 );
346
347 AddRenewal( $borrower_id1, $item_id1, $samplebranch1->{branchcode},
348     $datedue3, $daysago10 );
349 @renewcount = C4::Circulation::GetRenewCount($borrower_id1, $item_id1);
350 is_deeply(
351     \@renewcount,
352     [ 3, 3, 0 ],
353     "With issuing rules (renewal allowed, 1 remaining) and with a valid parameter, Getrenewcount of item1 returns 0 renews left"
354 );
355
356 $dbh->do("DELETE FROM old_issues");
357 AddReturn($barcode_1);
358 my $return = $dbh->selectrow_hashref("SELECT DATE(returndate) AS return_date, CURRENT_DATE() AS today FROM old_issues LIMIT 1" );
359 ok( $return->{return_date} eq $return->{today}, "Item returned with no return date specified has todays date" );
360
361 $dbh->do("DELETE FROM old_issues");
362 C4::Circulation::AddIssue( $borrower_1, $barcode_1, $daysago10, 0, $today );
363 AddReturn($barcode_1, undef, undef, undef, '2014-04-01 23:42');
364 $return = $dbh->selectrow_hashref("SELECT * FROM old_issues LIMIT 1" );
365 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" );
366
367 my $itemnumber;
368 ($biblionumber, $biblioitemnumber, $itemnumber) = C4::Items::AddItem(
369     {
370         barcode        => 'barcode_3',
371         itemcallnumber => 'callnumber3',
372         homebranch     => $samplebranch1->{branchcode},
373         holdingbranch  => $samplebranch1->{branchcode},
374         notforloan => 1,
375     },
376     $biblionumber
377 );
378
379 t::lib::Mocks::mock_preference( 'UpdateNotForLoanStatusOnCheckin', q{} );
380 AddReturn( 'barcode_3', $samplebranch1->{branchcode} );
381 my $item = GetItem( $itemnumber );
382 ok( $item->{notforloan} eq 1, 'UpdateNotForLoanStatusOnCheckin does not modify value when not enabled' );
383
384 t::lib::Mocks::mock_preference( 'UpdateNotForLoanStatusOnCheckin', '1: 9' );
385 AddReturn( 'barcode_3', $samplebranch1->{branchcode} );
386 $item = GetItem( $itemnumber );
387 ok( $item->{notforloan} eq 9, q{UpdateNotForLoanStatusOnCheckin updates notforloan value from 1 to 9 with setting "1: 9"} );
388
389 AddReturn( 'barcode_3', $samplebranch1->{branchcode} );
390 $item = GetItem( $itemnumber );
391 ok( $item->{notforloan} eq 9, q{UpdateNotForLoanStatusOnCheckin does not update notforloan value from 9 with setting "1: 9"} );
392
393 # Bug 14640 - Cancel the hold on checking out if asked
394 my $reserve_id = AddReserve('CPL', $borrower_id1, $biblionumber,
395     undef,  1, undef, undef, "a note", "a title", undef, '');
396 ok( $reserve_id, 'The reserve should have been inserted' );
397 AddIssue( $borrower_2, $barcode_1, dt_from_string, 'cancel' );
398 my $reserve = GetReserve( $reserve_id );
399 is( $reserve, undef, 'The reserve should have been correctly cancelled' );
400
401 #End transaction
402 $dbh->rollback;