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