Bug 14385: Extend OpacHiddenItems to allow specifying exempt borrower categories
[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 use Data::Dumper;
21
22 use MARC::Record;
23 use C4::Items;
24 use C4::Biblio;
25 use Koha::Items;
26 use Koha::Database;
27 use Koha::DateUtils qw( dt_from_string );
28 use Koha::Library;
29 use Koha::DateUtils;
30 use Koha::MarcSubfieldStructures;
31 use Koha::Caches;
32
33 use t::lib::Mocks;
34 use t::lib::TestBuilder;
35
36 use Test::More tests => 14;
37
38 use Test::Warn;
39
40 my $schema = Koha::Database->new->schema;
41 my $location = 'My Location';
42
43 subtest 'General Add, Get and Del tests' => sub {
44
45     plan tests => 16;
46
47     $schema->storage->txn_begin;
48
49     my $builder = t::lib::TestBuilder->new;
50     my $library = $builder->build({
51         source => 'Branch',
52     });
53     my $itemtype = $builder->build({
54         source => 'Itemtype',
55     });
56
57     # Create a biblio instance for testing
58     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
59     my ($bibnum, $bibitemnum) = get_biblio();
60
61     # Add an item.
62     my ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem({ homebranch => $library->{branchcode}, holdingbranch => $library->{branchcode}, location => $location, itype => $itemtype->{itemtype} } , $bibnum);
63     cmp_ok($item_bibnum, '==', $bibnum, "New item is linked to correct biblionumber.");
64     cmp_ok($item_bibitemnum, '==', $bibitemnum, "New item is linked to correct biblioitemnumber.");
65
66     # Get item.
67     my $getitem = GetItem($itemnumber);
68     cmp_ok($getitem->{'itemnumber'}, '==', $itemnumber, "Retrieved item has correct itemnumber.");
69     cmp_ok($getitem->{'biblioitemnumber'}, '==', $item_bibitemnum, "Retrieved item has correct biblioitemnumber.");
70     is( $getitem->{location}, $location, "The location should not have been modified" );
71     is( $getitem->{permanent_location}, $location, "The permanent_location should have been set to the location value" );
72
73
74     # Do not modify anything, and do not explode!
75     my $dbh = C4::Context->dbh;
76     local $dbh->{RaiseError} = 1;
77     ModItem({}, $bibnum, $itemnumber);
78
79     # Modify item; setting barcode.
80     ModItem({ barcode => '987654321' }, $bibnum, $itemnumber);
81     my $moditem = GetItem($itemnumber);
82     cmp_ok($moditem->{'barcode'}, '==', '987654321', 'Modified item barcode successfully to: '.$moditem->{'barcode'} . '.');
83
84     # Delete item.
85     DelItem({ biblionumber => $bibnum, itemnumber => $itemnumber });
86     my $getdeleted = GetItem($itemnumber);
87     is($getdeleted->{'itemnumber'}, undef, "Item deleted as expected.");
88
89     ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem({ homebranch => $library->{branchcode}, holdingbranch => $library->{branchcode}, location => $location, permanent_location => 'my permanent location', itype => $itemtype->{itemtype} } , $bibnum);
90     $getitem = GetItem($itemnumber);
91     is( $getitem->{location}, $location, "The location should not have been modified" );
92     is( $getitem->{permanent_location}, 'my permanent location', "The permanent_location should not have modified" );
93
94     ModItem({ location => $location }, $bibnum, $itemnumber);
95     $getitem = GetItem($itemnumber);
96     is( $getitem->{location}, $location, "The location should have been set to correct location" );
97     is( $getitem->{permanent_location}, $location, "The permanent_location should have been set to location" );
98
99     ModItem({ location => 'CART' }, $bibnum, $itemnumber);
100     $getitem = GetItem($itemnumber);
101     is( $getitem->{location}, 'CART', "The location should have been set to CART" );
102     is( $getitem->{permanent_location}, $location, "The permanent_location should not have been set to CART" );
103
104     t::lib::Mocks::mock_preference('item-level_itypes', '1');
105     $getitem = GetItem($itemnumber);
106     is( $getitem->{itype}, $itemtype->{itemtype}, "Itemtype set correctly when using item-level_itypes" );
107     t::lib::Mocks::mock_preference('item-level_itypes', '0');
108     $getitem = GetItem($itemnumber);
109     is( $getitem->{itype}, undef, "Itemtype set correctly when not using item-level_itypes" );
110
111     $schema->storage->txn_rollback;
112 };
113
114 subtest 'ModItem tests' => sub {
115     plan tests => 6;
116
117     $schema->storage->txn_begin;
118
119     my $builder = t::lib::TestBuilder->new;
120     my $item = $builder->build({
121         source => 'Item',
122         value  => {
123             itemlost     => 0,
124             damaged      => 0,
125             withdrawn    => 0,
126             itemlost_on  => undef,
127             damaged_on   => undef,
128             withdrawn_on => undef,
129         }
130     });
131
132     my @fields = qw( itemlost withdrawn damaged );
133     for my $field (@fields) {
134         $item->{$field} = 1;
135         ModItem( $item, $item->{biblionumber}, $item->{itemnumber} );
136         my $post_mod_item = Koha::Items->find({ itemnumber => $item->{itemnumber} })->unblessed;
137         is( output_pref({ str => $post_mod_item->{$field."_on"}, dateonly => 1 }), output_pref({ dt => dt_from_string(), dateonly => 1 }), "When updating $field, $field"."_on is updated" );
138
139         $item->{$field} = 0;
140         ModItem( $item, $item->{biblionumber}, $item->{itemnumber} );
141         $post_mod_item = Koha::Items->find({ itemnumber => $item->{itemnumber} })->unblessed;
142         is( $post_mod_item->{$field."_on"}, undef, "When clearing $field, $field"."_on is cleared" );
143     }
144
145     $schema->storage->txn_rollback;
146
147 };
148
149 subtest 'GetHiddenItemnumbers tests' => sub {
150
151     plan tests => 9;
152
153     # This sub is controlled by the OpacHiddenItems system preference.
154
155     $schema->storage->txn_begin;
156
157     my $builder = t::lib::TestBuilder->new;
158     my $library1 = $builder->build({
159         source => 'Branch',
160     });
161
162     my $library2 = $builder->build({
163         source => 'Branch',
164     });
165     my $itemtype = $builder->build({
166         source => 'Itemtype',
167     });
168
169     # Create a new biblio
170     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
171     my ($biblionumber, $biblioitemnumber) = get_biblio();
172
173     # Add two items
174     my ( $item1_bibnum, $item1_bibitemnum, $item1_itemnumber ) = AddItem(
175         {
176             homebranch    => $library1->{branchcode},
177             holdingbranch => $library1->{branchcode},
178             withdrawn     => 1,
179             itype         => $itemtype->{itemtype},
180         },
181         $biblionumber
182     );
183     my ( $item2_bibnum, $item2_bibitemnum, $item2_itemnumber ) = AddItem(
184         {
185             homebranch    => $library2->{branchcode},
186             holdingbranch => $library2->{branchcode},
187             withdrawn     => 0,
188             itype         => $itemtype->{itemtype},
189         },
190         $biblionumber
191     );
192
193     my $opachiddenitems;
194     my @itemnumbers = ($item1_itemnumber,$item2_itemnumber);
195     my @hidden;
196     my @items;
197     push @items, GetItem( $item1_itemnumber );
198     push @items, GetItem( $item2_itemnumber );
199
200     # Empty OpacHiddenItems
201     C4::Context->set_preference('OpacHiddenItems','');
202     ok( !defined( GetHiddenItemnumbers( { items => \@items } ) ),
203         "Hidden items list undef if OpacHiddenItems empty");
204
205     # Blank spaces
206     C4::Context->set_preference('OpacHiddenItems','  ');
207     ok( scalar GetHiddenItemnumbers( { items => \@items } ) == 0,
208         "Hidden items list empty if OpacHiddenItems only contains blanks");
209
210     # One variable / value
211     $opachiddenitems = "
212         withdrawn: [1]";
213     t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
214     @hidden = GetHiddenItemnumbers( { items => \@items } );
215     ok( scalar @hidden == 1, "Only one hidden item");
216     is( $hidden[0], $item1_itemnumber, "withdrawn=1 is hidden");
217
218     # One variable, two values
219     $opachiddenitems = "
220         withdrawn: [1,0]";
221     t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
222     C4::Context->set_preference( 'OpacHiddenItems', $opachiddenitems );
223     @hidden = GetHiddenItemnumbers( { items => \@items } );
224     ok( scalar @hidden == 2, "Two items hidden");
225     is_deeply( \@hidden, \@itemnumbers, "withdrawn=1 and withdrawn=0 hidden");
226
227     # Two variables, a value each
228     $opachiddenitems = "
229         withdrawn: [1]
230         homebranch: [$library2->{branchcode}]
231     ";
232     t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
233     @hidden = GetHiddenItemnumbers( { items => \@items } );
234     ok( scalar @hidden == 2, "Two items hidden");
235     is_deeply( \@hidden, \@itemnumbers, "withdrawn=1 and homebranch library2 hidden");
236
237     # Valid OpacHiddenItems, empty list
238     @items = ();
239     @hidden = GetHiddenItemnumbers( { items => \@items } );
240     ok( scalar @hidden == 0, "Empty items list, no item hidden");
241
242     $schema->storage->txn_rollback;
243 };
244
245 subtest 'GetItemsInfo tests' => sub {
246
247     plan tests => 4;
248
249     $schema->storage->txn_begin;
250
251     my $builder = t::lib::TestBuilder->new;
252     my $library1 = $builder->build({
253         source => 'Branch',
254     });
255     my $library2 = $builder->build({
256         source => 'Branch',
257     });
258     my $itemtype = $builder->build({
259         source => 'Itemtype',
260     });
261
262     # Add a biblio
263     my ($biblionumber, $biblioitemnumber) = get_biblio();
264     # Add an item
265     my ( $item_bibnum, $item_bibitemnum, $itemnumber ) = AddItem(
266         {
267             homebranch    => $library1->{branchcode},
268             holdingbranch => $library2->{branchcode},
269             itype         => $itemtype->{itemtype},
270         },
271         $biblionumber
272     );
273
274     my $library = Koha::Libraries->find( $library1->{branchcode} );
275     $library->opac_info("homebranch OPAC info");
276     $library->store;
277
278     $library = Koha::Libraries->find( $library2->{branchcode} );
279     $library->opac_info("holdingbranch OPAC info");
280     $library->store;
281
282     my @results = GetItemsInfo( $biblionumber );
283     ok( @results, 'GetItemsInfo returns results');
284     is( $results[0]->{ home_branch_opac_info }, "homebranch OPAC info",
285         'GetItemsInfo returns the correct home branch OPAC info notice' );
286     is( $results[0]->{ holding_branch_opac_info }, "holdingbranch OPAC info",
287         'GetItemsInfo returns the correct holding branch OPAC info notice' );
288     is( exists( $results[0]->{ onsite_checkout } ), 1,
289         'GetItemsInfo returns a onsite_checkout key' );
290
291     $schema->storage->txn_rollback;
292 };
293
294 subtest q{Test Koha::Database->schema()->resultset('Item')->itemtype()} => sub {
295
296     plan tests => 4;
297
298     $schema->storage->txn_begin;
299
300     my $biblio = $schema->resultset('Biblio')->create({
301         title       => "Test title",
302         datecreated => dt_from_string,
303         biblioitems => [ { itemtype => 'BIB_LEVEL' } ],
304     });
305     my $biblioitem = $biblio->biblioitems->first;
306     my $item = $schema->resultset('Item')->create({
307         biblioitemnumber => $biblioitem->biblioitemnumber,
308         biblionumber     => $biblio->biblionumber,
309         itype            => "ITEM_LEVEL",
310     });
311
312     t::lib::Mocks::mock_preference( 'item-level_itypes', 0 );
313     is( $item->effective_itemtype(), 'BIB_LEVEL', '$item->itemtype() returns biblioitem.itemtype when item-level_itypes is disabled' );
314
315     t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
316     is( $item->effective_itemtype(), 'ITEM_LEVEL', '$item->itemtype() returns items.itype when item-level_itypes is enabled' );
317
318     # If itemtype is not defined and item-level_level item types are set
319     # fallback to biblio-level itemtype (Bug 14651) and warn
320     $item->itype( undef );
321     $item->update();
322     my $effective_itemtype;
323     warning_is { $effective_itemtype = $item->effective_itemtype() }
324                 "item-level_itypes set but no itemtype set for item (".$item->itemnumber.")",
325                 '->effective_itemtype() raises a warning when falling back to bib-level';
326
327     ok( defined $effective_itemtype &&
328                 $effective_itemtype eq 'BIB_LEVEL',
329         '$item->effective_itemtype() falls back to biblioitems.itemtype when item-level_itypes is enabled but undef' );
330
331     $schema->storage->txn_rollback;
332 };
333
334 subtest 'SearchItems test' => sub {
335     plan tests => 14;
336
337     $schema->storage->txn_begin;
338     my $dbh = C4::Context->dbh;
339     my $builder = t::lib::TestBuilder->new;
340
341     my $library1 = $builder->build({
342         source => 'Branch',
343     });
344     my $library2 = $builder->build({
345         source => 'Branch',
346     });
347     my $itemtype = $builder->build({
348         source => 'Itemtype',
349     });
350
351     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
352     my $cpl_items_before = SearchItemsByField( 'homebranch', $library1->{branchcode});
353
354     my ($biblionumber) = get_biblio();
355
356     my (undef, $initial_items_count) = SearchItems(undef, {rows => 1});
357
358     # Add two items
359     my (undef, undef, $item1_itemnumber) = AddItem({
360         homebranch => $library1->{branchcode},
361         holdingbranch => $library1->{branchcode},
362         itype => $itemtype->{itemtype},
363     }, $biblionumber);
364     my (undef, undef, $item2_itemnumber) = AddItem({
365         homebranch => $library2->{branchcode},
366         holdingbranch => $library2->{branchcode},
367         itype => $itemtype->{itemtype},
368     }, $biblionumber);
369
370     my ($items, $total_results);
371
372     ($items, $total_results) = SearchItems();
373     is($total_results, $initial_items_count + 2, "Created 2 new items");
374     is(scalar @$items, $total_results, "SearchItems() returns all items");
375
376     ($items, $total_results) = SearchItems(undef, {rows => 1});
377     is($total_results, $initial_items_count + 2);
378     is(scalar @$items, 1, "SearchItems(undef, {rows => 1}) returns only 1 item");
379
380     # Search all items where homebranch = 'CPL'
381     my $filter = {
382         field => 'homebranch',
383         query => $library1->{branchcode},
384         operator => '=',
385     };
386     ($items, $total_results) = SearchItems($filter);
387     ok($total_results > 0, "There is at least one CPL item");
388     my $all_items_are_CPL = 1;
389     foreach my $item (@$items) {
390         if ($item->{homebranch} ne $library1->{branchcode}) {
391             $all_items_are_CPL = 0;
392             last;
393         }
394     }
395     ok($all_items_are_CPL, "All items returned by SearchItems are from CPL");
396
397     # Search all items where homebranch != 'CPL'
398     $filter = {
399         field => 'homebranch',
400         query => $library1->{branchcode},
401         operator => '!=',
402     };
403     ($items, $total_results) = SearchItems($filter);
404     ok($total_results > 0, "There is at least one non-CPL item");
405     my $all_items_are_not_CPL = 1;
406     foreach my $item (@$items) {
407         if ($item->{homebranch} eq $library1->{branchcode}) {
408             $all_items_are_not_CPL = 0;
409             last;
410         }
411     }
412     ok($all_items_are_not_CPL, "All items returned by SearchItems are not from CPL");
413
414     # Search all items where biblio title (245$a) is like 'Silence in the %'
415     $filter = {
416         field => 'marc:245$a',
417         query => 'Silence in the %',
418         operator => 'like',
419     };
420     ($items, $total_results) = SearchItems($filter);
421     ok($total_results >= 2, "There is at least 2 items with a biblio title like 'Silence in the %'");
422
423     # Search all items where biblio title is 'Silence in the library'
424     # and homebranch is 'CPL'
425     $filter = {
426         conjunction => 'AND',
427         filters => [
428             {
429                 field => 'marc:245$a',
430                 query => 'Silence in the %',
431                 operator => 'like',
432             },
433             {
434                 field => 'homebranch',
435                 query => $library1->{branchcode},
436                 operator => '=',
437             },
438         ],
439     };
440     ($items, $total_results) = SearchItems($filter);
441     my $found = 0;
442     foreach my $item (@$items) {
443         if ($item->{itemnumber} == $item1_itemnumber) {
444             $found = 1;
445             last;
446         }
447     }
448     ok($found, "item1 found");
449
450     my $frameworkcode = q||;
451     my ($itemfield) = GetMarcFromKohaField('items.itemnumber', $frameworkcode);
452
453     # Create item subfield 'z' without link
454     $dbh->do('DELETE FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield="z" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
455     $dbh->do('INSERT INTO marc_subfield_structure (tagfield, tagsubfield, frameworkcode) VALUES (?, "z", ?)', undef, $itemfield, $frameworkcode);
456
457     # Clear cache
458     my $cache = Koha::Caches->get_instance();
459     $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
460     $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
461     $cache->clear_from_cache("default_value_for_mod_marc-");
462     $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
463
464     my $item3_record = new MARC::Record;
465     $item3_record->append_fields(
466         new MARC::Field(
467             $itemfield, '', '',
468             'z' => 'foobar',
469             'y' => $itemtype->{itemtype}
470         )
471     );
472     my (undef, undef, $item3_itemnumber) = AddItemFromMarc($item3_record,
473         $biblionumber);
474
475     # Search item where item subfield z is "foobar"
476     $filter = {
477         field => 'marc:' . $itemfield . '$z',
478         query => 'foobar',
479         operator => 'like',
480     };
481     ($items, $total_results) = SearchItems($filter);
482     ok(scalar @$items == 1, 'found 1 item with $z = "foobar"');
483
484     # Link $z to items.itemnotes (and make sure there is no other subfields
485     # linked to it)
486     $dbh->do('DELETE FROM marc_subfield_structure WHERE kohafield="items.itemnotes" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
487     $dbh->do('UPDATE marc_subfield_structure SET kohafield="items.itemnotes" WHERE tagfield=? AND tagsubfield="z" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
488
489     # Clear cache
490     $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
491     $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
492     $cache->clear_from_cache("default_value_for_mod_marc-");
493     $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
494
495     ModItemFromMarc($item3_record, $biblionumber, $item3_itemnumber);
496
497     # Make sure the link is used
498     my $item3 = GetItem($item3_itemnumber);
499     ok($item3->{itemnotes} eq 'foobar', 'itemnotes eq "foobar"');
500
501     # Do the same search again.
502     # This time it will search in items.itemnotes
503     ($items, $total_results) = SearchItems($filter);
504     ok(scalar @$items == 1, 'found 1 item with itemnotes = "foobar"');
505
506     my $cpl_items_after = SearchItemsByField( 'homebranch', $library1->{branchcode});
507     is( ( scalar( @$cpl_items_after ) - scalar ( @$cpl_items_before ) ), 1, 'SearchItemsByField should return something' );
508
509     $schema->storage->txn_rollback;
510 };
511
512 subtest 'Koha::Item(s) tests' => sub {
513
514     plan tests => 5;
515
516     $schema->storage->txn_begin();
517
518     my $builder = t::lib::TestBuilder->new;
519     my $library1 = $builder->build({
520         source => 'Branch',
521     });
522     my $library2 = $builder->build({
523         source => 'Branch',
524     });
525     my $itemtype = $builder->build({
526         source => 'Itemtype',
527     });
528
529     # Create a biblio and item for testing
530     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
531     my ($bibnum, $bibitemnum) = get_biblio();
532     my ( $item_bibnum, $item_bibitemnum, $itemnumber ) = AddItem(
533         {
534             homebranch    => $library1->{branchcode},
535             holdingbranch => $library2->{branchcode},
536             itype         => $itemtype->{itemtype},
537         },
538         $bibnum
539     );
540
541     # Get item.
542     my $item = Koha::Items->find( $itemnumber );
543     is( ref($item), 'Koha::Item', "Got Koha::Item" );
544
545     my $homebranch = $item->home_branch();
546     is( ref($homebranch), 'Koha::Library', "Got Koha::Library from home_branch method" );
547     is( $homebranch->branchcode(), $library1->{branchcode}, "Home branch code matches homebranch" );
548
549     my $holdingbranch = $item->holding_branch();
550     is( ref($holdingbranch), 'Koha::Library', "Got Koha::Library from holding_branch method" );
551     is( $holdingbranch->branchcode(), $library2->{branchcode}, "Home branch code matches holdingbranch" );
552
553     $schema->storage->txn_rollback;
554 };
555
556 subtest 'C4::Biblio::EmbedItemsInMarcBiblio' => sub {
557     plan tests => 7;
558
559     $schema->storage->txn_begin();
560
561     my $builder = t::lib::TestBuilder->new;
562     my $library1 = $builder->build({
563         source => 'Branch',
564     });
565     my $library2 = $builder->build({
566         source => 'Branch',
567     });
568     my $itemtype = $builder->build({
569         source => 'Itemtype',
570     });
571
572     my ( $biblionumber, $biblioitemnumber ) = get_biblio();
573     my $item_infos = [
574         { homebranch => $library1->{branchcode}, holdingbranch => $library1->{branchcode} },
575         { homebranch => $library1->{branchcode}, holdingbranch => $library1->{branchcode} },
576         { homebranch => $library1->{branchcode}, holdingbranch => $library1->{branchcode} },
577         { homebranch => $library2->{branchcode}, holdingbranch => $library2->{branchcode} },
578         { homebranch => $library2->{branchcode}, holdingbranch => $library2->{branchcode} },
579         { homebranch => $library1->{branchcode}, holdingbranch => $library2->{branchcode} },
580         { homebranch => $library1->{branchcode}, holdingbranch => $library2->{branchcode} },
581         { homebranch => $library1->{branchcode}, holdingbranch => $library2->{branchcode} },
582     ];
583     my $number_of_items = scalar @$item_infos;
584     my $number_of_items_with_homebranch_is_CPL =
585       grep { $_->{homebranch} eq $library1->{branchcode} } @$item_infos;
586
587     my @itemnumbers;
588     for my $item_info (@$item_infos) {
589         my ( undef, undef, $itemnumber ) = AddItem(
590             {
591                 homebranch    => $item_info->{homebranch},
592                 holdingbranch => $item_info->{holdingbanch},
593                 itype         => $itemtype->{itemtype},
594             },
595             $biblionumber
596         );
597         push @itemnumbers, $itemnumber;
598     }
599
600     # Emptied the OpacHiddenItems pref
601     t::lib::Mocks::mock_preference( 'OpacHiddenItems', '' );
602
603     my ($itemfield) =
604       C4::Biblio::GetMarcFromKohaField( 'items.itemnumber', '' );
605     my $record = C4::Biblio::GetMarcBiblio({ biblionumber => $biblionumber });
606     warning_is { C4::Biblio::EmbedItemsInMarcBiblio() }
607     { carped => 'EmbedItemsInMarcBiblio: No MARC record passed' },
608       'Should crap is no record passed.';
609
610     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber );
611     my @items = $record->field($itemfield);
612     is( scalar @items, $number_of_items, 'Should return all items' );
613
614     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber,
615         [ $itemnumbers[1], $itemnumbers[3] ] );
616     @items = $record->field($itemfield);
617     is( scalar @items, 2, 'Should return all items present in the list' );
618
619     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber, undef, 1 );
620     @items = $record->field($itemfield);
621     is( scalar @items, $number_of_items, 'Should return all items for opac' );
622
623     my $opachiddenitems = "
624         homebranch: ['$library1->{branchcode}']";
625     t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
626
627     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber );
628     @items = $record->field($itemfield);
629     is( scalar @items,
630         $number_of_items,
631         'Even with OpacHiddenItems set, all items should have been embedded' );
632
633     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber, undef, 1 );
634     @items = $record->field($itemfield);
635     is(
636         scalar @items,
637         $number_of_items - $number_of_items_with_homebranch_is_CPL,
638 'For OPAC, the pref OpacHiddenItems should have been take into account. Only items with homebranch ne CPL should have been embedded'
639     );
640
641     $opachiddenitems = "
642         homebranch: ['$library1->{branchcode}', '$library2->{branchcode}']";
643     t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
644     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber, undef, 1 );
645     @items = $record->field($itemfield);
646     is(
647         scalar @items,
648         0,
649 'For OPAC, If all items are hidden, no item should have been embedded'
650     );
651
652     $schema->storage->txn_rollback;
653 };
654
655
656 subtest 'C4::Items::_build_default_values_for_mod_marc' => sub {
657     plan tests => 4;
658
659     $schema->storage->txn_begin();
660
661     my $builder = t::lib::TestBuilder->new;
662     my $framework = $builder->build({ source => 'BiblioFramework' });
663
664     # Link biblio.biblionumber and biblioitems.biblioitemnumber to avoid _koha_marc_update_bib_ids to fail with 'no biblio[item]number tag for framework"
665     Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => '999', tagsubfield => [ 'c', 'd' ] })->delete;
666     Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '999', tagsubfield => 'c', kohafield => 'biblio.biblionumber' })->store;
667     Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '999', tagsubfield => 'd', kohafield => 'biblioitems.biblioitemnumber' })->store;
668
669     # Same for item fields: itemnumber, barcode, itype
670     Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => '952', tagsubfield => [ '9', 'p', 'y' ] })->delete;
671     Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '952', tagsubfield => '9', kohafield => 'items.itemnumber' })->store;
672     Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '952', tagsubfield => 'p', kohafield => 'items.barcode' })->store;
673     Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '952', tagsubfield => 'y', kohafield => 'items.itype' })->store;
674     Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
675
676     my $itemtype = $builder->build({ source => 'Itemtype' })->{itemtype};
677
678     # Create a record with a barcode
679     my ($biblionumber) = get_biblio( $framework->{frameworkcode} );
680     my $item_record = new MARC::Record;
681     my $a_barcode = 'a barcode';
682     my $barcode_field = MARC::Field->new(
683         '952', ' ', ' ',
684         p => $a_barcode,
685         y => $itemtype
686     );
687     my $itemtype_field = MARC::Field->new(
688         '952', ' ', ' ',
689         y => $itemtype
690     );
691     $item_record->append_fields( $barcode_field );
692     my (undef, undef, $item_itemnumber) = AddItemFromMarc($item_record, $biblionumber);
693
694     # Make sure everything has been set up
695     my $item = GetItem($item_itemnumber);
696     is( $item->{barcode}, $a_barcode, 'Everything has been set up correctly, the barcode is defined as expected' );
697
698     # Delete the barcode field and save the record
699     $item_record->delete_fields( $barcode_field );
700     $item_record->append_fields( $itemtype_field ); # itemtype is mandatory
701     ModItemFromMarc($item_record, $biblionumber, $item_itemnumber);
702     $item = GetItem($item_itemnumber);
703     is( $item->{barcode}, undef, 'The default value should have been set to the barcode, the field is mapped to a kohafield' );
704
705     # Re-add the barcode field and save the record
706     $item_record->append_fields( $barcode_field );
707     ModItemFromMarc($item_record, $biblionumber, $item_itemnumber);
708     $item = GetItem($item_itemnumber);
709     is( $item->{barcode}, $a_barcode, 'Everything has been set up correctly, the barcode is defined as expected' );
710
711     # Remove the mapping for barcode
712     Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => '952', tagsubfield => 'p' })->delete;
713
714     # And make sure the caches are cleared
715     my $cache = Koha::Caches->get_instance();
716     $cache->clear_from_cache("default_value_for_mod_marc-");
717     $cache->clear_from_cache("MarcSubfieldStructure-");
718
719     # Update the MARC field with another value
720     $item_record->delete_fields( $barcode_field );
721     my $another_barcode = 'another_barcode';
722     my $another_barcode_field = MARC::Field->new(
723         '952', ' ', ' ',
724         p => $another_barcode,
725     );
726     $item_record->append_fields( $another_barcode_field );
727     # The DB value should not have been updated
728     ModItemFromMarc($item_record, $biblionumber, $item_itemnumber);
729     $item = GetItem($item_itemnumber);
730     is ( $item->{barcode}, $a_barcode, 'items.barcode is not mapped anymore, so the DB column has not been updated' );
731
732     $cache->clear_from_cache("default_value_for_mod_marc-");
733     $cache->clear_from_cache( "MarcSubfieldStructure-" );
734     $schema->storage->txn_rollback;
735 };
736
737 subtest '_mod_item_dates' => sub {
738     plan tests => 11;
739
740     is( C4::Items::_mod_item_dates(), undef, 'Call without parameters' );
741     is( C4::Items::_mod_item_dates(1), undef, 'Call without hashref' );
742
743     my $orgitem;
744     my $item = {
745         itemcallnumber  => 'V II 149 1963',
746         barcode         => '109304',
747     };
748     $orgitem = { %$item };
749     C4::Items::_mod_item_dates($item);
750     is_deeply( $item, $orgitem, 'No dates passed to _mod_item_dates' );
751
752     # add two correct dates
753     t::lib::Mocks::mock_preference('dateformat', 'us');
754     $item->{dateaccessioned} = '01/31/2016';
755     $item->{onloan} =  $item->{dateaccessioned};
756     $orgitem = { %$item };
757     C4::Items::_mod_item_dates($item);
758     is( $item->{dateaccessioned}, '2016-01-31', 'dateaccessioned is fine' );
759     is( $item->{onloan}, '2016-01-31', 'onloan is fine too' );
760
761
762     # add some invalid dates
763     $item->{notexistingcolumndate} = '13/1/2015'; # wrong format
764     $item->{anotherdate} = 'tralala'; # even worse
765     $item->{myzerodate} = '0000-00-00'; # wrong too
766     C4::Items::_mod_item_dates($item);
767     is( $item->{notexistingcolumndate}, undef, 'Invalid date became NULL' );
768     is( $item->{anotherdate}, undef, 'Second invalid date became NULL too' );
769     is( $item->{myzerodate}, undef, '0000-00-00 became NULL too' );
770
771     # check if itemlost_on was not touched
772     $item->{itemlost_on} = '12345678';
773     $item->{withdrawn_on} = '12/31/2015 23:59:00';
774     $item->{damaged_on} = '01/20/2017 09:00:00';
775     $orgitem = { %$item };
776     C4::Items::_mod_item_dates($item);
777     is_deeply( $item, $orgitem, 'Colums with _on are not touched' );
778
779     t::lib::Mocks::mock_preference('dateformat', 'metric');
780     $item->{dateaccessioned} = '01/31/2016'; #wrong
781     $item->{yetanotherdatetime} = '20/01/2016 13:58:00'; #okay
782     C4::Items::_mod_item_dates($item);
783     is( $item->{dateaccessioned}, undef, 'dateaccessioned wrong format' );
784     is( $item->{yetanotherdatetime}, '2016-01-20 13:58:00',
785         'yetanotherdatetime is ok' );
786 };
787
788 subtest 'get_hostitemnumbers_of' => sub {
789     plan tests => 1;
790
791     $schema->storage->txn_begin;
792
793     my $bib = MARC::Record->new();
794     $bib->append_fields(
795         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
796         MARC::Field->new('245', ' ', ' ', a => 'Silence in the library'),
797         MARC::Field->new('773', ' ', ' ', b => 'b without 0 or 9'),
798     );
799     my ($biblionumber, $bibitemnum) = AddBiblio($bib, '');
800
801     my @itemnumbers = C4::Items::get_hostitemnumbers_of( $biblionumber );
802     is( @itemnumbers, 0, );
803
804     $schema->storage->txn_rollback;
805 };
806
807 subtest 'Test logging for ModItem' => sub {
808
809     plan tests => 3;
810
811     t::lib::Mocks::mock_preference('CataloguingLog', 1);
812
813     $schema->storage->txn_begin;
814
815     my $builder = t::lib::TestBuilder->new;
816     my $library = $builder->build({
817         source => 'Branch',
818     });
819     my $itemtype = $builder->build({
820         source => 'Itemtype',
821     });
822
823     # Create a biblio instance for testing
824     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
825     my ($bibnum, $bibitemnum) = get_biblio();
826
827     # Add an item.
828     my ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem({ homebranch => $library->{branchcode}, holdingbranch => $library->{branchcode}, location => $location, itype => $itemtype->{itemtype} } , $bibnum);
829
830     # False means no logging
831     $schema->resultset('ActionLog')->search()->delete();
832     ModItem({ location => $location }, $bibnum, $itemnumber, { log_action => 0 });
833     is( $schema->resultset('ActionLog')->count(), 0, 'False value does not trigger logging' );
834
835     # True means logging
836     $schema->resultset('ActionLog')->search()->delete();
837     ModItem({ location => $location }, $bibnum, $itemnumber, { log_action => 1 });
838     is( $schema->resultset('ActionLog')->count(), 1, 'True value does trigger logging' );
839
840     # Undefined defaults to true
841     $schema->resultset('ActionLog')->search()->delete();
842     ModItem({ location => $location }, $bibnum, $itemnumber);
843     is( $schema->resultset('ActionLog')->count(), 1, 'Undefined value defaults to true, triggers logging' );
844
845     $schema->storage->txn_rollback;
846 };
847
848 subtest 'Check stockrotationitem relationship' => sub {
849     plan tests => 1;
850
851     $schema->storage->txn_begin();
852
853     my $builder = t::lib::TestBuilder->new;
854     my $item = $builder->build({ source => 'Item' });
855
856     $builder->build({
857         source => 'Stockrotationitem',
858         value  => { itemnumber_id => $item->{itemnumber} }
859     });
860
861     my $sritem = Koha::Items->find($item->{itemnumber})->stockrotationitem;
862     isa_ok( $sritem, 'Koha::StockRotationItem', "Relationship works and correctly creates Koha::Object." );
863
864     $schema->storage->txn_rollback;
865 };
866
867 subtest 'Check add_to_rota method' => sub {
868     plan tests => 2;
869
870     $schema->storage->txn_begin();
871
872     my $builder = t::lib::TestBuilder->new;
873     my $item = $builder->build({ source => 'Item' });
874     my $rota = $builder->build({ source => 'Stockrotationrota' });
875     my $srrota = Koha::StockRotationRotas->find($rota->{rota_id});
876
877     $builder->build({
878         source => 'Stockrotationstage',
879         value  => { rota_id => $rota->{rota_id} },
880     });
881
882     my $sritem = Koha::Items->find($item->{itemnumber});
883     $sritem->add_to_rota($rota->{rota_id});
884
885     is(
886         Koha::StockRotationItems->find($item->{itemnumber})->stage_id,
887         $srrota->stockrotationstages->next->stage_id,
888         "Adding to a rota a new sritem item being assigned to its first stage."
889     );
890
891     my $newrota = $builder->build({ source => 'Stockrotationrota' });
892
893     my $srnewrota = Koha::StockRotationRotas->find($newrota->{rota_id});
894
895     $builder->build({
896         source => 'Stockrotationstage',
897         value  => { rota_id => $newrota->{rota_id} },
898     });
899
900     $sritem->add_to_rota($newrota->{rota_id});
901
902     is(
903         Koha::StockRotationItems->find($item->{itemnumber})->stage_id,
904         $srnewrota->stockrotationstages->next->stage_id,
905         "Moving an item results in that sritem being assigned to the new first stage."
906     );
907
908     $schema->storage->txn_rollback;
909 };
910
911 # Helper method to set up a Biblio.
912 sub get_biblio {
913     my ( $frameworkcode ) = @_;
914     $frameworkcode //= '';
915     my $bib = MARC::Record->new();
916     $bib->append_fields(
917         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
918         MARC::Field->new('245', ' ', ' ', a => 'Silence in the library'),
919     );
920     my ($bibnum, $bibitemnum) = AddBiblio($bib, $frameworkcode);
921     return ($bibnum, $bibitemnum);
922 }