Bug 7634: Make the tests pass
[koha.git] / t / db_dependent / Items.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 under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation; either version 2 of the License, or (at your option) any later
8 # version.
9 #
10 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along
15 # with Koha; if not, write to the Free Software Foundation, Inc.,
16 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17 #
18
19 use Modern::Perl;
20
21 use MARC::Record;
22 use C4::Biblio;
23 use C4::Branch;
24 use Koha::Database;
25
26 use Test::More tests => 8;
27 use Test::Warn;
28
29 BEGIN {
30     use_ok('C4::Items');
31     use_ok('Koha::Items');
32 }
33
34 my $dbh = C4::Context->dbh;
35 my $branches = GetBranches;
36 my ($branch1, $branch2) = keys %$branches;
37
38 subtest 'General Add, Get and Del tests' => sub {
39
40     plan tests => 6;
41
42     # Start transaction
43     $dbh->{AutoCommit} = 0;
44     $dbh->{RaiseError} = 1;
45
46     # Create a biblio instance for testing
47     C4::Context->set_preference('marcflavour', 'MARC21');
48     my ($bibnum, $bibitemnum) = get_biblio();
49
50     # Add an item.
51     my ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem({ homebranch => $branch1, holdingbranch => $branch1 } , $bibnum);
52     cmp_ok($item_bibnum, '==', $bibnum, "New item is linked to correct biblionumber.");
53     cmp_ok($item_bibitemnum, '==', $bibitemnum, "New item is linked to correct biblioitemnumber.");
54
55     # Get item.
56     my $getitem = GetItem($itemnumber);
57     cmp_ok($getitem->{'itemnumber'}, '==', $itemnumber, "Retrieved item has correct itemnumber.");
58     cmp_ok($getitem->{'biblioitemnumber'}, '==', $item_bibitemnum, "Retrieved item has correct biblioitemnumber.");
59
60     # Modify item; setting barcode.
61     ModItem({ barcode => '987654321' }, $bibnum, $itemnumber);
62     my $moditem = GetItem($itemnumber);
63     cmp_ok($moditem->{'barcode'}, '==', '987654321', 'Modified item barcode successfully to: '.$moditem->{'barcode'} . '.');
64
65     # Delete item.
66     DelItem({ biblionumber => $bibnum, itemnumber => $itemnumber });
67     my $getdeleted = GetItem($itemnumber);
68     is($getdeleted->{'itemnumber'}, undef, "Item deleted as expected.");
69
70     $dbh->rollback;
71 };
72
73 subtest 'GetHiddenItemnumbers tests' => sub {
74
75     plan tests => 9;
76
77     # This sub is controlled by the OpacHiddenItems system preference.
78
79     # Start transaction
80     $dbh->{AutoCommit} = 0;
81     $dbh->{RaiseError} = 1;
82
83     # Create a new biblio
84     C4::Context->set_preference('marcflavour', 'MARC21');
85     my ($biblionumber, $biblioitemnumber) = get_biblio();
86
87     # Add branches if they don't exist
88     if (not defined GetBranchDetail('CPL')) {
89         ModBranch({add => 1, branchcode => 'CPL', branchname => 'Centerville'});
90     }
91     if (not defined GetBranchDetail('MPL')) {
92         ModBranch({add => 1, branchcode => 'MPL', branchname => 'Midway'});
93     }
94
95     # Add two items
96     my ($item1_bibnum, $item1_bibitemnum, $item1_itemnumber) = AddItem(
97             { homebranch => $branch1,
98               holdingbranch => $branch1,
99               withdrawn => 1 },
100             $biblionumber
101     );
102     my ($item2_bibnum, $item2_bibitemnum, $item2_itemnumber) = AddItem(
103             { homebranch => $branch2,
104               holdingbranch => $branch2,
105               withdrawn => 0 },
106             $biblionumber
107     );
108
109     my $opachiddenitems;
110     my @itemnumbers = ($item1_itemnumber,$item2_itemnumber);
111     my @hidden;
112     my @items;
113     push @items, GetItem( $item1_itemnumber );
114     push @items, GetItem( $item2_itemnumber );
115
116     # Empty OpacHiddenItems
117     C4::Context->set_preference('OpacHiddenItems','');
118     ok( !defined( GetHiddenItemnumbers( @items ) ),
119         "Hidden items list undef if OpacHiddenItems empty");
120
121     # Blank spaces
122     C4::Context->set_preference('OpacHiddenItems','  ');
123     ok( scalar GetHiddenItemnumbers( @items ) == 0,
124         "Hidden items list empty if OpacHiddenItems only contains blanks");
125
126     # One variable / value
127     $opachiddenitems = "
128         withdrawn: [1]";
129     C4::Context->set_preference( 'OpacHiddenItems', $opachiddenitems );
130     @hidden = GetHiddenItemnumbers( @items );
131     ok( scalar @hidden == 1, "Only one hidden item");
132     is( $hidden[0], $item1_itemnumber, "withdrawn=1 is hidden");
133
134     # One variable, two values
135     $opachiddenitems = "
136         withdrawn: [1,0]";
137     C4::Context->set_preference( 'OpacHiddenItems', $opachiddenitems );
138     @hidden = GetHiddenItemnumbers( @items );
139     ok( scalar @hidden == 2, "Two items hidden");
140     is_deeply( \@hidden, \@itemnumbers, "withdrawn=1 and withdrawn=0 hidden");
141
142     # Two variables, a value each
143     $opachiddenitems = "
144         withdrawn: [1]
145         homebranch: [$branch2]
146     ";
147     C4::Context->set_preference( 'OpacHiddenItems', $opachiddenitems );
148     @hidden = GetHiddenItemnumbers( @items );
149     ok( scalar @hidden == 2, "Two items hidden");
150     is_deeply( \@hidden, \@itemnumbers, "withdrawn=1 and homebranch=MPL hidden");
151
152     # Valid OpacHiddenItems, empty list
153     @items = ();
154     @hidden = GetHiddenItemnumbers( @items );
155     ok( scalar @hidden == 0, "Empty items list, no item hidden");
156
157     $dbh->rollback;
158 };
159
160 subtest 'GetItemsInfo tests' => sub {
161
162     plan tests => 4;
163
164     # Start transaction
165     $dbh->{AutoCommit} = 0;
166     $dbh->{RaiseError} = 1;
167
168     # Add a biblio
169     my ($biblionumber, $biblioitemnumber) = get_biblio();
170     # Add an item
171     my ($item_bibnum, $item_bibitemnum, $itemnumber)
172         = AddItem({
173                 homebranch    => $branch1,
174                 holdingbranch => $branch2
175             }, $biblionumber );
176
177     my $branch = GetBranchDetail( $branch1 );
178     $branch->{ opac_info } = "homebranch OPAC info";
179     ModBranch($branch);
180
181     $branch = GetBranchDetail( $branch2 );
182     $branch->{ opac_info } = "holdingbranch OPAC info";
183     ModBranch($branch);
184
185     my @results = GetItemsInfo( $biblionumber );
186     ok( @results, 'GetItemsInfo returns results');
187     is( $results[0]->{ home_branch_opac_info }, "homebranch OPAC info",
188         'GetItemsInfo returns the correct home branch OPAC info notice' );
189     is( $results[0]->{ holding_branch_opac_info }, "holdingbranch OPAC info",
190         'GetItemsInfo returns the correct holding branch OPAC info notice' );
191     is( exists( $results[0]->{ onsite_checkout } ), 1,
192         'GetItemsInfo returns a onsite_checkout key' );
193
194     $dbh->rollback;
195 };
196
197 subtest q{Test Koha::Database->schema()->resultset('Item')->itemtype()} => sub {
198
199     plan tests => 4;
200
201     # Start transaction
202     $dbh->{AutoCommit} = 0;
203     $dbh->{RaiseError} = 1;
204
205     my $schema = Koha::Database->new()->schema();
206
207     my $biblio =
208     $schema->resultset('Biblio')->create(
209         {
210             title       => "Test title",
211             biblioitems => [
212                 {
213                     itemtype => 'BIB_LEVEL',
214                     items    => [ { itype => "ITEM_LEVEL" } ]
215                 }
216             ]
217         }
218     );
219
220     my @bi = $biblio->biblioitems();
221     my ( $item ) = $bi[0]->items();
222
223     C4::Context->set_preference( 'item-level_itypes', 0 );
224     ok( $item->effective_itemtype() eq 'BIB_LEVEL', '$item->itemtype() returns biblioitem.itemtype when item-level_itypes is disabled' );
225
226     C4::Context->set_preference( 'item-level_itypes', 1 );
227     ok( $item->effective_itemtype() eq 'ITEM_LEVEL', '$item->itemtype() returns items.itype when item-level_itypes is enabled' );
228
229     # If itemtype is not defined and item-level_level item types are set
230     # fallback to biblio-level itemtype (Bug 14651) and warn
231     $item->itype( undef );
232     $item->update();
233     my $effective_itemtype;
234     warning_is { $effective_itemtype = $item->effective_itemtype() }
235                 "item-level_itypes set but no itemtype set for item ($item->itemnumber)",
236                 '->effective_itemtype() raises a warning when falling back to bib-level';
237
238     ok( defined $effective_itemtype &&
239                 $effective_itemtype eq 'BIB_LEVEL',
240         '$item->effective_itemtype() falls back to biblioitems.itemtype when item-level_itypes is enabled but undef' );
241
242     $dbh->rollback;
243 };
244
245 subtest 'SearchItems test' => sub {
246     plan tests => 14;
247
248     # Start transaction
249     $dbh->{AutoCommit} = 0;
250     $dbh->{RaiseError} = 1;
251
252     C4::Context->set_preference('marcflavour', 'MARC21');
253     my $cpl_items_before = SearchItemsByField( 'homebranch', 'CPL');
254
255     my ($biblionumber) = get_biblio();
256
257     # Add branches if they don't exist
258     if (not defined GetBranchDetail('CPL')) {
259         ModBranch({add => 1, branchcode => 'CPL', branchname => 'Centerville'});
260     }
261     if (not defined GetBranchDetail('MPL')) {
262         ModBranch({add => 1, branchcode => 'MPL', branchname => 'Midway'});
263     }
264
265     my (undef, $initial_items_count) = SearchItems(undef, {rows => 1});
266
267     # Add two items
268     my (undef, undef, $item1_itemnumber) = AddItem({
269         homebranch => 'CPL',
270         holdingbranch => 'CPL',
271     }, $biblionumber);
272     my (undef, undef, $item2_itemnumber) = AddItem({
273         homebranch => 'MPL',
274         holdingbranch => 'MPL',
275     }, $biblionumber);
276
277     my ($items, $total_results);
278
279     ($items, $total_results) = SearchItems();
280     is($total_results, $initial_items_count + 2, "Created 2 new items");
281     is(scalar @$items, $total_results, "SearchItems() returns all items");
282
283     ($items, $total_results) = SearchItems(undef, {rows => 1});
284     is($total_results, $initial_items_count + 2);
285     is(scalar @$items, 1, "SearchItems(undef, {rows => 1}) returns only 1 item");
286
287     # Search all items where homebranch = 'CPL'
288     my $filter = {
289         field => 'homebranch',
290         query => 'CPL',
291         operator => '=',
292     };
293     ($items, $total_results) = SearchItems($filter);
294     ok($total_results > 0, "There is at least one CPL item");
295     my $all_items_are_CPL = 1;
296     foreach my $item (@$items) {
297         if ($item->{homebranch} ne 'CPL') {
298             $all_items_are_CPL = 0;
299             last;
300         }
301     }
302     ok($all_items_are_CPL, "All items returned by SearchItems are from CPL");
303
304     # Search all items where homebranch != 'CPL'
305     $filter = {
306         field => 'homebranch',
307         query => 'CPL',
308         operator => '!=',
309     };
310     ($items, $total_results) = SearchItems($filter);
311     ok($total_results > 0, "There is at least one non-CPL item");
312     my $all_items_are_not_CPL = 1;
313     foreach my $item (@$items) {
314         if ($item->{homebranch} eq 'CPL') {
315             $all_items_are_not_CPL = 0;
316             last;
317         }
318     }
319     ok($all_items_are_not_CPL, "All items returned by SearchItems are not from CPL");
320
321     # Search all items where biblio title (245$a) is like 'Silence in the %'
322     $filter = {
323         field => 'marc:245$a',
324         query => 'Silence in the %',
325         operator => 'like',
326     };
327     ($items, $total_results) = SearchItems($filter);
328     ok($total_results >= 2, "There is at least 2 items with a biblio title like 'Silence in the %'");
329
330     # Search all items where biblio title is 'Silence in the library'
331     # and homebranch is 'CPL'
332     $filter = {
333         conjunction => 'AND',
334         filters => [
335             {
336                 field => 'marc:245$a',
337                 query => 'Silence in the %',
338                 operator => 'like',
339             },
340             {
341                 field => 'homebranch',
342                 query => 'CPL',
343                 operator => '=',
344             },
345         ],
346     };
347     ($items, $total_results) = SearchItems($filter);
348     my $found = 0;
349     foreach my $item (@$items) {
350         if ($item->{itemnumber} == $item1_itemnumber) {
351             $found = 1;
352             last;
353         }
354     }
355     ok($found, "item1 found");
356
357     my ($itemfield) = GetMarcFromKohaField('items.itemnumber', '');
358
359     # Create item subfield 'z' without link
360     $dbh->do('DELETE FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield="z" AND frameworkcode=""', undef, $itemfield);
361     $dbh->do('INSERT INTO marc_subfield_structure (tagfield, tagsubfield, frameworkcode) VALUES (?, "z", "")', undef, $itemfield);
362
363     # Clear cache
364     $C4::Context::context->{marcfromkohafield} = undef;
365     $C4::Biblio::inverted_field_map = undef;
366
367     my $item3_record = new MARC::Record;
368     $item3_record->append_fields(
369         new MARC::Field($itemfield, '', '', 'z' => 'foobar')
370     );
371     my (undef, undef, $item3_itemnumber) = AddItemFromMarc($item3_record,
372         $biblionumber);
373
374     # Search item where item subfield z is "foobar"
375     $filter = {
376         field => 'marc:' . $itemfield . '$z',
377         query => 'foobar',
378         operator => 'like',
379     };
380     ($items, $total_results) = SearchItems($filter);
381     ok(scalar @$items == 1, 'found 1 item with $z = "foobar"');
382
383     # Link $z to items.itemnotes (and make sure there is no other subfields
384     # linked to it)
385     $dbh->do('DELETE FROM marc_subfield_structure WHERE kohafield="items.itemnotes" AND frameworkcode=""', undef, $itemfield);
386     $dbh->do('UPDATE marc_subfield_structure SET kohafield="items.itemnotes" WHERE tagfield=? AND tagsubfield="z" AND frameworkcode=""', undef, $itemfield);
387
388     # Clear cache
389     $C4::Context::context->{marcfromkohafield} = undef;
390     $C4::Biblio::inverted_field_map = undef;
391
392     ModItemFromMarc($item3_record, $biblionumber, $item3_itemnumber);
393
394     # Make sure the link is used
395     my $item3 = GetItem($item3_itemnumber);
396     ok($item3->{itemnotes} eq 'foobar', 'itemnotes eq "foobar"');
397
398     # Do the same search again.
399     # This time it will search in items.itemnotes
400     ($items, $total_results) = SearchItems($filter);
401     ok(scalar @$items == 1, 'found 1 item with itemnotes = "foobar"');
402
403     my $cpl_items_after = SearchItemsByField( 'homebranch', 'CPL');
404     is( ( scalar( @$cpl_items_after ) - scalar ( @$cpl_items_before ) ), 1, 'SearchItemsByField should return something' );
405
406     $dbh->rollback;
407 };
408
409 subtest 'Koha::Item(s) tests' => sub {
410
411     plan tests => 5;
412
413     # Start transaction
414     my $schema = Koha::Database->new()->schema();
415     $schema->storage->txn_begin();
416     $dbh->{RaiseError} = 1;
417
418     # Create a biblio and item for testing
419     C4::Context->set_preference('marcflavour', 'MARC21');
420     my ($bibnum, $bibitemnum) = get_biblio();
421     my ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem({ homebranch => $branch1, holdingbranch => $branch2 } , $bibnum);
422
423     # Get item.
424     my $item = Koha::Items->find( $itemnumber );
425     is( ref($item), 'Koha::Item', "Got Koha::Item" );
426
427     my $homebranch = $item->home_branch();
428     is( ref($homebranch), 'Koha::Branch', "Got Koha::Branch from home_branch method" );
429     is( $homebranch->branchcode(), $branch1, "Home branch code matches homebranch" );
430
431     my $holdingbranch = $item->holding_branch();
432     is( ref($holdingbranch), 'Koha::Branch', "Got Koha::Branch from holding_branch method" );
433     is( $holdingbranch->branchcode(), $branch2, "Home branch code matches holdingbranch" );
434 };
435
436 # Helper method to set up a Biblio.
437 sub get_biblio {
438     my $bib = MARC::Record->new();
439     $bib->append_fields(
440         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
441         MARC::Field->new('245', ' ', ' ', a => 'Silence in the library'),
442     );
443     my ($bibnum, $bibitemnum) = AddBiblio($bib, '');
444     return ($bibnum, $bibitemnum);
445 }