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