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