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