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