Bug 14651: (regression test) fallback to bib-level if itype is undef
[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 ($biblionumber) = get_biblio();
254
255     # Add branches if they don't exist
256     if (not defined GetBranchDetail('CPL')) {
257         ModBranch({add => 1, branchcode => 'CPL', branchname => 'Centerville'});
258     }
259     if (not defined GetBranchDetail('MPL')) {
260         ModBranch({add => 1, branchcode => 'MPL', branchname => 'Midway'});
261     }
262
263     my (undef, $initial_items_count) = SearchItems(undef, {rows => 1});
264
265     # Add two items
266     my (undef, undef, $item1_itemnumber) = AddItem({
267         homebranch => 'CPL',
268         holdingbranch => 'CPL',
269     }, $biblionumber);
270     my (undef, undef, $item2_itemnumber) = AddItem({
271         homebranch => 'MPL',
272         holdingbranch => 'MPL',
273     }, $biblionumber);
274
275     my ($items, $total_results);
276
277     ($items, $total_results) = SearchItems();
278     is($total_results, $initial_items_count + 2, "Created 2 new items");
279     is(scalar @$items, $total_results, "SearchItems() returns all items");
280
281     ($items, $total_results) = SearchItems(undef, {rows => 1});
282     is($total_results, $initial_items_count + 2);
283     is(scalar @$items, 1, "SearchItems(undef, {rows => 1}) returns only 1 item");
284
285     # Search all items where homebranch = 'CPL'
286     my $filter = {
287         field => 'homebranch',
288         query => 'CPL',
289         operator => '=',
290     };
291     ($items, $total_results) = SearchItems($filter);
292     ok($total_results > 0, "There is at least one CPL item");
293     my $all_items_are_CPL = 1;
294     foreach my $item (@$items) {
295         if ($item->{homebranch} ne 'CPL') {
296             $all_items_are_CPL = 0;
297             last;
298         }
299     }
300     ok($all_items_are_CPL, "All items returned by SearchItems are from CPL");
301
302     # Search all items where homebranch != 'CPL'
303     $filter = {
304         field => 'homebranch',
305         query => 'CPL',
306         operator => '!=',
307     };
308     ($items, $total_results) = SearchItems($filter);
309     ok($total_results > 0, "There is at least one non-CPL item");
310     my $all_items_are_not_CPL = 1;
311     foreach my $item (@$items) {
312         if ($item->{homebranch} eq 'CPL') {
313             $all_items_are_not_CPL = 0;
314             last;
315         }
316     }
317     ok($all_items_are_not_CPL, "All items returned by SearchItems are not from CPL");
318
319     # Search all items where biblio title (245$a) is like 'Silence in the %'
320     $filter = {
321         field => 'marc:245$a',
322         query => 'Silence in the %',
323         operator => 'like',
324     };
325     ($items, $total_results) = SearchItems($filter);
326     ok($total_results >= 2, "There is at least 2 items with a biblio title like 'Silence in the %'");
327
328     # Search all items where biblio title is 'Silence in the library'
329     # and homebranch is 'CPL'
330     $filter = {
331         conjunction => 'AND',
332         filters => [
333             {
334                 field => 'marc:245$a',
335                 query => 'Silence in the %',
336                 operator => 'like',
337             },
338             {
339                 field => 'homebranch',
340                 query => 'CPL',
341                 operator => '=',
342             },
343         ],
344     };
345     ($items, $total_results) = SearchItems($filter);
346     my $found = 0;
347     foreach my $item (@$items) {
348         if ($item->{itemnumber} == $item1_itemnumber) {
349             $found = 1;
350             last;
351         }
352     }
353     ok($found, "item1 found");
354
355     my ($itemfield) = GetMarcFromKohaField('items.itemnumber', '');
356
357     # Create item subfield 'z' without link
358     $dbh->do('DELETE FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield="z" AND frameworkcode=""', undef, $itemfield);
359     $dbh->do('INSERT INTO marc_subfield_structure (tagfield, tagsubfield, frameworkcode) VALUES (?, "z", "")', undef, $itemfield);
360
361     # Clear cache
362     $C4::Context::context->{marcfromkohafield} = undef;
363     $C4::Biblio::inverted_field_map = undef;
364
365     my $item3_record = new MARC::Record;
366     $item3_record->append_fields(
367         new MARC::Field($itemfield, '', '', 'z' => 'foobar')
368     );
369     my (undef, undef, $item3_itemnumber) = AddItemFromMarc($item3_record,
370         $biblionumber);
371
372     # Search item where item subfield z is "foobar"
373     $filter = {
374         field => 'marc:' . $itemfield . '$z',
375         query => 'foobar',
376         operator => 'like',
377     };
378     ($items, $total_results) = SearchItems($filter);
379     ok(scalar @$items == 1, 'found 1 item with $z = "foobar"');
380
381     # Link $z to items.itemnotes (and make sure there is no other subfields
382     # linked to it)
383     $dbh->do('DELETE FROM marc_subfield_structure WHERE kohafield="items.itemnotes" AND frameworkcode=""', undef, $itemfield);
384     $dbh->do('UPDATE marc_subfield_structure SET kohafield="items.itemnotes" WHERE tagfield=? AND tagsubfield="z" AND frameworkcode=""', undef, $itemfield);
385
386     # Clear cache
387     $C4::Context::context->{marcfromkohafield} = undef;
388     $C4::Biblio::inverted_field_map = undef;
389
390     ModItemFromMarc($item3_record, $biblionumber, $item3_itemnumber);
391
392     # Make sure the link is used
393     my $item3 = GetItem($item3_itemnumber);
394     ok($item3->{itemnotes} eq 'foobar', 'itemnotes eq "foobar"');
395
396     # Do the same search again.
397     # This time it will search in items.itemnotes
398     ($items, $total_results) = SearchItems($filter);
399     ok(scalar @$items == 1, 'found 1 item with itemnotes = "foobar"');
400
401     my $cpl_items = SearchItemsByField( 'homebranch', 'CPL');
402     is( ( $cpl_items and scalar( @$cpl_items ) ), 1, 'SearchItemsByField should return something' );
403
404     $dbh->rollback;
405 };
406
407 subtest 'Koha::Item(s) tests' => sub {
408
409     plan tests => 5;
410
411     # Start transaction
412     my $schema = Koha::Database->new()->schema();
413     $schema->storage->txn_begin();
414     $dbh->{RaiseError} = 1;
415
416     # Create a biblio and item for testing
417     C4::Context->set_preference('marcflavour', 'MARC21');
418     my ($bibnum, $bibitemnum) = get_biblio();
419     my ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem({ homebranch => $branch1, holdingbranch => $branch2 } , $bibnum);
420
421     # Get item.
422     my $item = Koha::Items->find( $itemnumber );
423     is( ref($item), 'Koha::Item', "Got Koha::Item" );
424
425     my $homebranch = $item->home_branch();
426     is( ref($homebranch), 'Koha::Branch', "Got Koha::Branch from home_branch method" );
427     is( $homebranch->branchcode(), $branch1, "Home branch code matches homebranch" );
428
429     my $holdingbranch = $item->holding_branch();
430     is( ref($holdingbranch), 'Koha::Branch', "Got Koha::Branch from holding_branch method" );
431     is( $holdingbranch->branchcode(), $branch2, "Home branch code matches holdingbranch" );
432 };
433
434 # Helper method to set up a Biblio.
435 sub get_biblio {
436     my $bib = MARC::Record->new();
437     $bib->append_fields(
438         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
439         MARC::Field->new('245', ' ', ' ', a => 'Silence in the library'),
440     );
441     my ($bibnum, $bibitemnum) = AddBiblio($bib, '');
442     return ($bibnum, $bibitemnum);
443 }