Bug 15081: (followup) Make test files using TestBuilder handle their transactions
[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 $biblio =
220     $schema->resultset('Biblio')->create(
221         {
222             title       => "Test title",
223             biblioitems => [
224                 {
225                     itemtype => 'BIB_LEVEL',
226                     items    => [ { itype => "ITEM_LEVEL" } ]
227                 }
228             ]
229         }
230     );
231
232     my @bi = $biblio->biblioitems();
233     my ( $item ) = $bi[0]->items();
234
235     C4::Context->set_preference( 'item-level_itypes', 0 );
236     ok( $item->effective_itemtype() eq 'BIB_LEVEL', '$item->itemtype() returns biblioitem.itemtype when item-level_itypes is disabled' );
237
238     C4::Context->set_preference( 'item-level_itypes', 1 );
239     ok( $item->effective_itemtype() eq 'ITEM_LEVEL', '$item->itemtype() returns items.itype when item-level_itypes is enabled' );
240
241     # If itemtype is not defined and item-level_level item types are set
242     # fallback to biblio-level itemtype (Bug 14651) and warn
243     $item->itype( undef );
244     $item->update();
245     my $effective_itemtype;
246     warning_is { $effective_itemtype = $item->effective_itemtype() }
247                 "item-level_itypes set but no itemtype set for item ($item->itemnumber)",
248                 '->effective_itemtype() raises a warning when falling back to bib-level';
249
250     ok( defined $effective_itemtype &&
251                 $effective_itemtype eq 'BIB_LEVEL',
252         '$item->effective_itemtype() falls back to biblioitems.itemtype when item-level_itypes is enabled but undef' );
253
254     $schema->storage->txn_rollback;
255 };
256
257 subtest 'SearchItems test' => sub {
258     plan tests => 14;
259
260     $schema->storage->txn_begin;
261     my $dbh = C4::Context->dbh;
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     $schema->storage->txn_rollback;
418 };
419
420 subtest 'Koha::Item(s) tests' => sub {
421
422     plan tests => 5;
423
424     $schema->storage->txn_begin();
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 subtest 'C4::Biblio::EmbedItemsInMarcBiblio' => sub {
445     plan tests => 7;
446
447     $schema->storage->txn_begin();
448
449     my ( $biblionumber, $biblioitemnumber ) = get_biblio();
450     my $item_infos = [
451         { homebranch => 'CPL', holdingbranch => 'CPL' },
452         { homebranch => 'CPL', holdingbranch => 'CPL' },
453         { homebranch => 'CPL', holdingbranch => 'CPL' },
454         { homebranch => 'MPL', holdingbranch => 'MPL' },
455         { homebranch => 'MPL', holdingbranch => 'MPL' },
456         { homebranch => 'CPL', holdingbranch => 'MPL' },
457         { homebranch => 'CPL', holdingbranch => 'MPL' },
458         { homebranch => 'CPL', holdingbranch => 'MPL' },
459     ];
460     my $number_of_items = scalar @$item_infos;
461     my $number_of_items_with_homebranch_is_CPL =
462       grep { $_->{homebranch} eq 'CPL' } @$item_infos;
463
464     my @itemnumbers;
465     for my $item_info (@$item_infos) {
466         my ( undef, undef, $itemnumber ) = AddItem(
467             {
468                 homebranch    => $item_info->{homebranch},
469                 holdingbranch => $item_info->{holdingbanch}
470             },
471             $biblionumber
472         );
473         push @itemnumbers, $itemnumber;
474     }
475
476     # Emptied the OpacHiddenItems pref
477     t::lib::Mocks::mock_preference( 'OpacHiddenItems', '' );
478
479     my ($itemfield) =
480       C4::Biblio::GetMarcFromKohaField( 'items.itemnumber', '' );
481     my $record = C4::Biblio::GetMarcBiblio($biblionumber);
482     warning_is { C4::Biblio::EmbedItemsInMarcBiblio() }
483     { carped => 'EmbedItemsInMarcBiblio: No MARC record passed' },
484       'Should crap is no record passed.';
485
486     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber );
487     my @items = $record->field($itemfield);
488     is( scalar @items, $number_of_items, 'Should return all items' );
489
490     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber,
491         [ $itemnumbers[1], $itemnumbers[3] ] );
492     @items = $record->field($itemfield);
493     is( scalar @items, 2, 'Should return all items present in the list' );
494
495     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber, undef, 1 );
496     @items = $record->field($itemfield);
497     is( scalar @items, $number_of_items, 'Should return all items for opac' );
498
499     my $opachiddenitems = "
500         homebranch: ['CPL']";
501     t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
502
503     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber );
504     @items = $record->field($itemfield);
505     is( scalar @items,
506         $number_of_items,
507         'Even with OpacHiddenItems set, all items should have been embeded' );
508
509     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber, undef, 1 );
510     @items = $record->field($itemfield);
511     is(
512         scalar @items,
513         $number_of_items - $number_of_items_with_homebranch_is_CPL,
514 'For OPAC, the pref OpacHiddenItems should have been take into account. Only items with homebranch ne CPL should have been embeded'
515     );
516
517     $opachiddenitems = "
518         homebranch: ['CPL', 'MPL']";
519     t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
520     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber, undef, 1 );
521     @items = $record->field($itemfield);
522     is(
523         scalar @items,
524         0,
525 'For OPAC, If all items are hidden, no item should have been embeded'
526     );
527 };
528
529 # Helper method to set up a Biblio.
530 sub get_biblio {
531     my $bib = MARC::Record->new();
532     $bib->append_fields(
533         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
534         MARC::Field->new('245', ' ', ' ', a => 'Silence in the library'),
535     );
536     my ($bibnum, $bibitemnum) = AddBiblio($bib, '');
537     return ($bibnum, $bibitemnum);
538 }