Bug 15505: Mark Hold Items 'On hold' instead of 'Available'
[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 $biblio = $builder->build_sample_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} } , $biblio->biblionumber);
64     cmp_ok($item_bibnum, '==', $biblio->biblionumber, "New item is linked to correct biblionumber.");
65     cmp_ok($item_bibitemnum, '==', $biblio->biblioitem->biblioitemnumber, "New item is linked to correct biblioitemnumber.");
66
67     # Get item.
68     my $getitem = Koha::Items->find($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({}, $biblio->biblionumber, $itemnumber);
79
80     # Modify item; setting barcode.
81     ModItem({ barcode => '987654321' }, $biblio->biblionumber, $itemnumber);
82     my $moditem = Koha::Items->find($itemnumber);
83     cmp_ok($moditem->barcode, '==', '987654321', 'Modified item barcode successfully to: '.$moditem->barcode . '.');
84
85     # Delete item.
86     DelItem({ biblionumber => $biblio->biblionumber, itemnumber => $itemnumber });
87     my $getdeleted = Koha::Items->find($itemnumber);
88     is($getdeleted, 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} } , $biblio->biblionumber);
91     $getitem = Koha::Items->find($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 }, $biblio->biblionumber, $itemnumber);
96     $getitem = Koha::Items->find($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' }, $biblio->biblionumber, $itemnumber);
101     $getitem = Koha::Items->find($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 = Koha::Items->find($itemnumber);
107     is( $getitem->effective_itemtype, $itemtype->{itemtype}, "Itemtype set correctly when using item-level_itypes" );
108     t::lib::Mocks::mock_preference('item-level_itypes', '0');
109     $getitem = Koha::Items->find($itemnumber);
110     is( $getitem->effective_itemtype, $biblio->biblioitem->itemtype, "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 $biblio = $builder->build_sample_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         $biblio->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         $biblio->biblionumber
192     );
193
194     my $opachiddenitems;
195     my @itemnumbers = ($item1_itemnumber,$item2_itemnumber);
196     my @hidden;
197     my @items;
198     push @items, Koha::Items->find( $item1_itemnumber )->unblessed;
199     push @items, Koha::Items->find( $item2_itemnumber )->unblessed;
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 => 9;
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 $biblio = $builder->build_sample_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         $biblio->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( $biblio->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     t::lib::Mocks::mock_preference( 'AllowItemsOnHoldCheckout', 0 );
317     #place item into holds queue
318     my $dbh = C4::Context->dbh;
319     $dbh->do(q{INSERT INTO tmp_holdsqueue (biblionumber, itemnumber, surname, borrowernumber ) VALUES (?, ?, "Zorro", 42)}, undef, $item_bibnum, $itemnumber);
320     @results = GetItemsInfo( $biblio->biblionumber );
321     is( $results[0]->{ pending_hold }, "1",
322         'Hold marked as pending/unavailable if not AllowItemsOnHoldCheckout' );
323     t::lib::Mocks::mock_preference( 'AllowItemsOnHoldCheckout', 1 );
324     @results = GetItemsInfo( $biblio->biblionumber );
325     is( $results[0]->{ pending_hold }, undef,
326         'Hold not marked as pending/unavailable if AllowItemsOnHoldCheckout' );
327
328
329     $schema->storage->txn_rollback;
330 };
331
332 subtest q{Test Koha::Database->schema()->resultset('Item')->itemtype()} => sub {
333
334     plan tests => 4;
335
336     $schema->storage->txn_begin;
337
338     my $biblio = $schema->resultset('Biblio')->create({
339         title       => "Test title",
340         datecreated => dt_from_string,
341         biblioitems => [ { itemtype => 'BIB_LEVEL' } ],
342     });
343     my $biblioitem = $biblio->biblioitems->first;
344     my $item = $schema->resultset('Item')->create({
345         biblioitemnumber => $biblioitem->biblioitemnumber,
346         biblionumber     => $biblio->biblionumber,
347         itype            => "ITEM_LEVEL",
348     });
349
350     t::lib::Mocks::mock_preference( 'item-level_itypes', 0 );
351     is( $item->effective_itemtype(), 'BIB_LEVEL', '$item->itemtype() returns biblioitem.itemtype when item-level_itypes is disabled' );
352
353     t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
354     is( $item->effective_itemtype(), 'ITEM_LEVEL', '$item->itemtype() returns items.itype when item-level_itypes is enabled' );
355
356     # If itemtype is not defined and item-level_level item types are set
357     # fallback to biblio-level itemtype (Bug 14651) and warn
358     $item->itype( undef );
359     $item->update();
360     my $effective_itemtype;
361     warning_is { $effective_itemtype = $item->effective_itemtype() }
362                 "item-level_itypes set but no itemtype set for item (".$item->itemnumber.")",
363                 '->effective_itemtype() raises a warning when falling back to bib-level';
364
365     ok( defined $effective_itemtype &&
366                 $effective_itemtype eq 'BIB_LEVEL',
367         '$item->effective_itemtype() falls back to biblioitems.itemtype when item-level_itypes is enabled but undef' );
368
369     $schema->storage->txn_rollback;
370 };
371
372 subtest 'SearchItems test' => sub {
373     plan tests => 14;
374
375     $schema->storage->txn_begin;
376     my $dbh = C4::Context->dbh;
377     my $builder = t::lib::TestBuilder->new;
378
379     my $library1 = $builder->build({
380         source => 'Branch',
381     });
382     my $library2 = $builder->build({
383         source => 'Branch',
384     });
385     my $itemtype = $builder->build({
386         source => 'Itemtype',
387     });
388
389     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
390     my $cpl_items_before = SearchItemsByField( 'homebranch', $library1->{branchcode});
391
392     my $biblio = $builder->build_sample_biblio({ title => 'Silence in the library' });
393     $builder->build_sample_biblio({ title => 'Silence in the shadow' });
394
395     my (undef, $initial_items_count) = SearchItems(undef, {rows => 1});
396
397     # Add two items
398     my (undef, undef, $item1_itemnumber) = AddItem({
399         homebranch => $library1->{branchcode},
400         holdingbranch => $library1->{branchcode},
401         itype => $itemtype->{itemtype},
402     }, $biblio->biblionumber);
403     my (undef, undef, $item2_itemnumber) = AddItem({
404         homebranch => $library2->{branchcode},
405         holdingbranch => $library2->{branchcode},
406         itype => $itemtype->{itemtype},
407     }, $biblio->biblionumber);
408
409     my ($items, $total_results);
410
411     ($items, $total_results) = SearchItems();
412     is($total_results, $initial_items_count + 2, "Created 2 new items");
413     is(scalar @$items, $total_results, "SearchItems() returns all items");
414
415     ($items, $total_results) = SearchItems(undef, {rows => 1});
416     is($total_results, $initial_items_count + 2);
417     is(scalar @$items, 1, "SearchItems(undef, {rows => 1}) returns only 1 item");
418
419     # Search all items where homebranch = 'CPL'
420     my $filter = {
421         field => 'homebranch',
422         query => $library1->{branchcode},
423         operator => '=',
424     };
425     ($items, $total_results) = SearchItems($filter);
426     ok($total_results > 0, "There is at least one CPL item");
427     my $all_items_are_CPL = 1;
428     foreach my $item (@$items) {
429         if ($item->{homebranch} ne $library1->{branchcode}) {
430             $all_items_are_CPL = 0;
431             last;
432         }
433     }
434     ok($all_items_are_CPL, "All items returned by SearchItems are from CPL");
435
436     # Search all items where homebranch != 'CPL'
437     $filter = {
438         field => 'homebranch',
439         query => $library1->{branchcode},
440         operator => '!=',
441     };
442     ($items, $total_results) = SearchItems($filter);
443     ok($total_results > 0, "There is at least one non-CPL item");
444     my $all_items_are_not_CPL = 1;
445     foreach my $item (@$items) {
446         if ($item->{homebranch} eq $library1->{branchcode}) {
447             $all_items_are_not_CPL = 0;
448             last;
449         }
450     }
451     ok($all_items_are_not_CPL, "All items returned by SearchItems are not from CPL");
452
453     # Search all items where biblio title (245$a) is like 'Silence in the %'
454     $filter = {
455         field => 'marc:245$a',
456         query => 'Silence in the %',
457         operator => 'like',
458     };
459     ($items, $total_results) = SearchItems($filter);
460     ok($total_results >= 2, "There is at least 2 items with a biblio title like 'Silence in the %'");
461
462     # Search all items where biblio title is 'Silence in the library'
463     # and homebranch is 'CPL'
464     $filter = {
465         conjunction => 'AND',
466         filters => [
467             {
468                 field => 'marc:245$a',
469                 query => 'Silence in the %',
470                 operator => 'like',
471             },
472             {
473                 field => 'homebranch',
474                 query => $library1->{branchcode},
475                 operator => '=',
476             },
477         ],
478     };
479     ($items, $total_results) = SearchItems($filter);
480     my $found = 0;
481     foreach my $item (@$items) {
482         if ($item->{itemnumber} == $item1_itemnumber) {
483             $found = 1;
484             last;
485         }
486     }
487     ok($found, "item1 found");
488
489     my $frameworkcode = q||;
490     my ($itemfield) = GetMarcFromKohaField('items.itemnumber', $frameworkcode);
491
492     # Create item subfield 'z' without link
493     $dbh->do('DELETE FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield="z" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
494     $dbh->do('INSERT INTO marc_subfield_structure (tagfield, tagsubfield, frameworkcode) VALUES (?, "z", ?)', undef, $itemfield, $frameworkcode);
495
496     # Clear cache
497     my $cache = Koha::Caches->get_instance();
498     $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
499     $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
500     $cache->clear_from_cache("default_value_for_mod_marc-");
501     $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
502
503     my $item3_record = new MARC::Record;
504     $item3_record->append_fields(
505         new MARC::Field(
506             $itemfield, '', '',
507             'z' => 'foobar',
508             'y' => $itemtype->{itemtype}
509         )
510     );
511     my (undef, undef, $item3_itemnumber) = AddItemFromMarc($item3_record,
512         $biblio->biblionumber);
513
514     # Search item where item subfield z is "foobar"
515     $filter = {
516         field => 'marc:' . $itemfield . '$z',
517         query => 'foobar',
518         operator => 'like',
519     };
520     ($items, $total_results) = SearchItems($filter);
521     ok(scalar @$items == 1, 'found 1 item with $z = "foobar"');
522
523     # Link $z to items.itemnotes (and make sure there is no other subfields
524     # linked to it)
525     $dbh->do('DELETE FROM marc_subfield_structure WHERE kohafield="items.itemnotes" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
526     $dbh->do('UPDATE marc_subfield_structure SET kohafield="items.itemnotes" WHERE tagfield=? AND tagsubfield="z" AND frameworkcode=?', undef, $itemfield, $frameworkcode);
527
528     # Clear cache
529     $cache->clear_from_cache("MarcStructure-0-$frameworkcode");
530     $cache->clear_from_cache("MarcStructure-1-$frameworkcode");
531     $cache->clear_from_cache("default_value_for_mod_marc-");
532     $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode");
533
534     ModItemFromMarc($item3_record, $biblio->biblionumber, $item3_itemnumber);
535
536     # Make sure the link is used
537     my $item3 = Koha::Items->find($item3_itemnumber);
538     ok($item3->itemnotes eq 'foobar', 'itemnotes eq "foobar"');
539
540     # Do the same search again.
541     # This time it will search in items.itemnotes
542     ($items, $total_results) = SearchItems($filter);
543     ok(scalar @$items == 1, 'found 1 item with itemnotes = "foobar"');
544
545     my $cpl_items_after = SearchItemsByField( 'homebranch', $library1->{branchcode});
546     is( ( scalar( @$cpl_items_after ) - scalar ( @$cpl_items_before ) ), 1, 'SearchItemsByField should return something' );
547
548     $schema->storage->txn_rollback;
549 };
550
551 subtest 'Koha::Item(s) tests' => sub {
552
553     plan tests => 5;
554
555     $schema->storage->txn_begin();
556
557     my $builder = t::lib::TestBuilder->new;
558     my $library1 = $builder->build({
559         source => 'Branch',
560     });
561     my $library2 = $builder->build({
562         source => 'Branch',
563     });
564     my $itemtype = $builder->build({
565         source => 'Itemtype',
566     });
567
568     # Create a biblio and item for testing
569     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
570     my $biblio = $builder->build_sample_biblio();
571     my ( $item_bibnum, $item_bibitemnum, $itemnumber ) = AddItem(
572         {
573             homebranch    => $library1->{branchcode},
574             holdingbranch => $library2->{branchcode},
575             itype         => $itemtype->{itemtype},
576         },
577         $biblio->biblionumber
578     );
579
580     # Get item.
581     my $item = Koha::Items->find( $itemnumber );
582     is( ref($item), 'Koha::Item', "Got Koha::Item" );
583
584     my $homebranch = $item->home_branch();
585     is( ref($homebranch), 'Koha::Library', "Got Koha::Library from home_branch method" );
586     is( $homebranch->branchcode(), $library1->{branchcode}, "Home branch code matches homebranch" );
587
588     my $holdingbranch = $item->holding_branch();
589     is( ref($holdingbranch), 'Koha::Library', "Got Koha::Library from holding_branch method" );
590     is( $holdingbranch->branchcode(), $library2->{branchcode}, "Home branch code matches holdingbranch" );
591
592     $schema->storage->txn_rollback;
593 };
594
595 subtest 'C4::Biblio::EmbedItemsInMarcBiblio' => sub {
596     plan tests => 8;
597
598     $schema->storage->txn_begin();
599
600     my $builder = t::lib::TestBuilder->new;
601     my $library1 = $builder->build({
602         source => 'Branch',
603     });
604     my $library2 = $builder->build({
605         source => 'Branch',
606     });
607     my $itemtype = $builder->build({
608         source => 'Itemtype',
609     });
610
611     my $biblio = $builder->build_sample_biblio();
612     my $item_infos = [
613         { homebranch => $library1->{branchcode}, holdingbranch => $library1->{branchcode} },
614         { homebranch => $library1->{branchcode}, holdingbranch => $library1->{branchcode} },
615         { homebranch => $library1->{branchcode}, holdingbranch => $library1->{branchcode} },
616         { homebranch => $library2->{branchcode}, holdingbranch => $library2->{branchcode} },
617         { homebranch => $library2->{branchcode}, holdingbranch => $library2->{branchcode} },
618         { homebranch => $library1->{branchcode}, holdingbranch => $library2->{branchcode} },
619         { homebranch => $library1->{branchcode}, holdingbranch => $library2->{branchcode} },
620         { homebranch => $library1->{branchcode}, holdingbranch => $library2->{branchcode} },
621     ];
622     my $number_of_items = scalar @$item_infos;
623     my $number_of_items_with_homebranch_is_CPL =
624       grep { $_->{homebranch} eq $library1->{branchcode} } @$item_infos;
625
626     my @itemnumbers;
627     for my $item_info (@$item_infos) {
628         my ( undef, undef, $itemnumber ) = AddItem(
629             {
630                 homebranch    => $item_info->{homebranch},
631                 holdingbranch => $item_info->{holdingbanch},
632                 itype         => $itemtype->{itemtype},
633             },
634             $biblio->biblionumber
635         );
636         push @itemnumbers, $itemnumber;
637     }
638
639     # Emptied the OpacHiddenItems pref
640     t::lib::Mocks::mock_preference( 'OpacHiddenItems', '' );
641
642     my ($itemfield) =
643       C4::Biblio::GetMarcFromKohaField( 'items.itemnumber', '' );
644     my $record = C4::Biblio::GetMarcBiblio({ biblionumber => $biblio->biblionumber });
645     warning_is { C4::Biblio::EmbedItemsInMarcBiblio() }
646     { carped => 'EmbedItemsInMarcBiblio: No MARC record passed' },
647       'Should carp is no record passed.';
648
649     C4::Biblio::EmbedItemsInMarcBiblio({
650         marc_record  => $record,
651         biblionumber => $biblio->biblionumber });
652     my @items = $record->field($itemfield);
653     is( scalar @items, $number_of_items, 'Should return all items' );
654
655     my $marc_with_items = C4::Biblio::GetMarcBiblio({
656         biblionumber => $biblio->biblionumber,
657         embed_items  => 1 });
658     is_deeply( $record, $marc_with_items, 'A direct call to GetMarcBiblio with items matches');
659
660     C4::Biblio::EmbedItemsInMarcBiblio({
661         marc_record  => $record,
662         biblionumber => $biblio->biblionumber,
663         item_numbers => [ $itemnumbers[1], $itemnumbers[3] ] });
664     @items = $record->field($itemfield);
665     is( scalar @items, 2, 'Should return all items present in the list' );
666
667     C4::Biblio::EmbedItemsInMarcBiblio({
668         marc_record  => $record,
669         biblionumber => $biblio->biblionumber,
670         opac         => 1 });
671     @items = $record->field($itemfield);
672     is( scalar @items, $number_of_items, 'Should return all items for opac' );
673
674     my $opachiddenitems = "
675         homebranch: ['$library1->{branchcode}']";
676     t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
677
678     C4::Biblio::EmbedItemsInMarcBiblio({
679         marc_record  => $record,
680         biblionumber => $biblio->biblionumber });
681     @items = $record->field($itemfield);
682     is( scalar @items,
683         $number_of_items,
684         'Even with OpacHiddenItems set, all items should have been embedded' );
685
686     C4::Biblio::EmbedItemsInMarcBiblio({
687         marc_record  => $record,
688         biblionumber => $biblio->biblionumber,
689         opac         => 1 });
690     @items = $record->field($itemfield);
691     is(
692         scalar @items,
693         $number_of_items - $number_of_items_with_homebranch_is_CPL,
694 'For OPAC, the pref OpacHiddenItems should have been take into account. Only items with homebranch ne CPL should have been embedded'
695     );
696
697     $opachiddenitems = "
698         homebranch: ['$library1->{branchcode}', '$library2->{branchcode}']";
699     t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems );
700     C4::Biblio::EmbedItemsInMarcBiblio({
701         marc_record  => $record,
702         biblionumber => $biblio->biblionumber,
703         opac         => 1 });
704     @items = $record->field($itemfield);
705     is(
706         scalar @items,
707         0,
708 'For OPAC, If all items are hidden, no item should have been embedded'
709     );
710
711     $schema->storage->txn_rollback;
712 };
713
714
715 subtest 'C4::Items::_build_default_values_for_mod_marc' => sub {
716     plan tests => 4;
717
718     $schema->storage->txn_begin();
719
720     my $builder = t::lib::TestBuilder->new;
721     my $framework = $builder->build({ source => 'BiblioFramework' });
722
723     # Link biblio.biblionumber and biblioitems.biblioitemnumber to avoid _koha_marc_update_bib_ids to fail with 'no biblio[item]number tag for framework"
724     Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => '999', tagsubfield => [ 'c', 'd' ] })->delete;
725     Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '999', tagsubfield => 'c', kohafield => 'biblio.biblionumber' })->store;
726     Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '999', tagsubfield => 'd', kohafield => 'biblioitems.biblioitemnumber' })->store;
727
728     # Same for item fields: itemnumber, barcode, itype
729     Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => '952', tagsubfield => [ '9', 'p', 'y' ] })->delete;
730     Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '952', tagsubfield => '9', kohafield => 'items.itemnumber' })->store;
731     Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '952', tagsubfield => 'p', kohafield => 'items.barcode' })->store;
732     Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '952', tagsubfield => 'y', kohafield => 'items.itype' })->store;
733     Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
734
735     my $itemtype = $builder->build({ source => 'Itemtype' })->{itemtype};
736
737     # Create a record with a barcode
738     my $biblio = $builder->build_sample_biblio({ frameworkcode => $framework->{frameworkcode} });
739     my $item_record = new MARC::Record;
740     my $a_barcode = 'a barcode';
741     my $barcode_field = MARC::Field->new(
742         '952', ' ', ' ',
743         p => $a_barcode,
744         y => $itemtype
745     );
746     my $itemtype_field = MARC::Field->new(
747         '952', ' ', ' ',
748         y => $itemtype
749     );
750     $item_record->append_fields( $barcode_field );
751     my (undef, undef, $item_itemnumber) = AddItemFromMarc($item_record, $biblio->biblionumber);
752
753     # Make sure everything has been set up
754     my $item = Koha::Items->find($item_itemnumber);
755     is( $item->barcode, $a_barcode, 'Everything has been set up correctly, the barcode is defined as expected' );
756
757     # Delete the barcode field and save the record
758     $item_record->delete_fields( $barcode_field );
759     $item_record->append_fields( $itemtype_field ); # itemtype is mandatory
760     ModItemFromMarc($item_record, $biblio->biblionumber, $item_itemnumber);
761     $item = Koha::Items->find($item_itemnumber);
762     is( $item->barcode, undef, 'The default value should have been set to the barcode, the field is mapped to a kohafield' );
763
764     # Re-add the barcode field and save the record
765     $item_record->append_fields( $barcode_field );
766     ModItemFromMarc($item_record, $biblio->biblionumber, $item_itemnumber);
767     $item = Koha::Items->find($item_itemnumber);
768     is( $item->barcode, $a_barcode, 'Everything has been set up correctly, the barcode is defined as expected' );
769
770     # Remove the mapping for barcode
771     Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => '952', tagsubfield => 'p' })->delete;
772
773     # And make sure the caches are cleared
774     my $cache = Koha::Caches->get_instance();
775     $cache->clear_from_cache("default_value_for_mod_marc-");
776     $cache->clear_from_cache("MarcSubfieldStructure-");
777
778     # Update the MARC field with another value
779     $item_record->delete_fields( $barcode_field );
780     my $another_barcode = 'another_barcode';
781     my $another_barcode_field = MARC::Field->new(
782         '952', ' ', ' ',
783         p => $another_barcode,
784     );
785     $item_record->append_fields( $another_barcode_field );
786     # The DB value should not have been updated
787     ModItemFromMarc($item_record, $biblio->biblionumber, $item_itemnumber);
788     $item = Koha::Items->find($item_itemnumber);
789     is ( $item->barcode, $a_barcode, 'items.barcode is not mapped anymore, so the DB column has not been updated' );
790
791     $cache->clear_from_cache("default_value_for_mod_marc-");
792     $cache->clear_from_cache( "MarcSubfieldStructure-" );
793     $schema->storage->txn_rollback;
794 };
795
796 subtest '_mod_item_dates' => sub {
797     plan tests => 11;
798
799     is( C4::Items::_mod_item_dates(), undef, 'Call without parameters' );
800     is( C4::Items::_mod_item_dates(1), undef, 'Call without hashref' );
801
802     my $orgitem;
803     my $item = {
804         itemcallnumber  => 'V II 149 1963',
805         barcode         => '109304',
806     };
807     $orgitem = { %$item };
808     C4::Items::_mod_item_dates($item);
809     is_deeply( $item, $orgitem, 'No dates passed to _mod_item_dates' );
810
811     # add two correct dates
812     t::lib::Mocks::mock_preference('dateformat', 'us');
813     $item->{dateaccessioned} = '01/31/2016';
814     $item->{onloan} =  $item->{dateaccessioned};
815     $orgitem = { %$item };
816     C4::Items::_mod_item_dates($item);
817     is( $item->{dateaccessioned}, '2016-01-31', 'dateaccessioned is fine' );
818     is( $item->{onloan}, '2016-01-31', 'onloan is fine too' );
819
820
821     # add some invalid dates
822     $item->{notexistingcolumndate} = '13/1/2015'; # wrong format
823     $item->{anotherdate} = 'tralala'; # even worse
824     $item->{myzerodate} = '0000-00-00'; # wrong too
825     C4::Items::_mod_item_dates($item);
826     is( $item->{notexistingcolumndate}, undef, 'Invalid date became NULL' );
827     is( $item->{anotherdate}, undef, 'Second invalid date became NULL too' );
828     is( $item->{myzerodate}, undef, '0000-00-00 became NULL too' );
829
830     # check if itemlost_on was not touched
831     $item->{itemlost_on} = '12345678';
832     $item->{withdrawn_on} = '12/31/2015 23:59:00';
833     $item->{damaged_on} = '01/20/2017 09:00:00';
834     $orgitem = { %$item };
835     C4::Items::_mod_item_dates($item);
836     is_deeply( $item, $orgitem, 'Colums with _on are not touched' );
837
838     t::lib::Mocks::mock_preference('dateformat', 'metric');
839     $item->{dateaccessioned} = '01/31/2016'; #wrong
840     $item->{yetanotherdatetime} = '20/01/2016 13:58:00'; #okay
841     C4::Items::_mod_item_dates($item);
842     is( $item->{dateaccessioned}, undef, 'dateaccessioned wrong format' );
843     is( $item->{yetanotherdatetime}, '2016-01-20 13:58:00',
844         'yetanotherdatetime is ok' );
845 };
846
847 subtest 'get_hostitemnumbers_of' => sub {
848     plan tests => 3;
849
850     $schema->storage->txn_begin;
851     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
852     my $builder = t::lib::TestBuilder->new;
853
854     # Host item field without 0 or 9
855     my $bib1 = MARC::Record->new();
856     $bib1->append_fields(
857         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
858         MARC::Field->new('245', ' ', ' ', a => 'Silence in the library'),
859         MARC::Field->new('773', ' ', ' ', b => 'b without 0 or 9'),
860     );
861     my ($biblionumber1, $bibitemnum1) = AddBiblio($bib1, '');
862     my @itemnumbers1 = C4::Items::get_hostitemnumbers_of( $biblionumber1 );
863     is( scalar @itemnumbers1, 0, '773 without 0 or 9');
864
865     # Correct host item field, analytical records on
866     t::lib::Mocks::mock_preference('EasyAnalyticalRecords', 1);
867     my $hostitem = $builder->build_sample_item();
868     my $bib2 = MARC::Record->new();
869     $bib2->append_fields(
870         MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'),
871         MARC::Field->new('245', ' ', ' ', a => 'Silence in the library'),
872         MARC::Field->new('773', ' ', ' ', 0 => $hostitem->biblionumber , 9 => $hostitem->itemnumber, b => 'b' ),
873     );
874     my ($biblionumber2, $bibitemnum2) = AddBiblio($bib2, '');
875     my @itemnumbers2 = C4::Items::get_hostitemnumbers_of( $biblionumber2 );
876     is( scalar @itemnumbers2, 1, '773 with 0 and 9, EasyAnalyticalRecords on');
877
878     # Correct host item field, analytical records off
879     t::lib::Mocks::mock_preference('EasyAnalyticalRecords', 0);
880     @itemnumbers2 = C4::Items::get_hostitemnumbers_of( $biblionumber2 );
881     is( scalar @itemnumbers2, 0, '773 with 0 and 9, EasyAnalyticalRecords off');
882
883     $schema->storage->txn_rollback;
884 };
885
886 subtest 'Test logging for ModItem' => sub {
887
888     plan tests => 3;
889
890     t::lib::Mocks::mock_preference('CataloguingLog', 1);
891
892     $schema->storage->txn_begin;
893
894     my $builder = t::lib::TestBuilder->new;
895     my $library = $builder->build({
896         source => 'Branch',
897     });
898     my $itemtype = $builder->build({
899         source => 'Itemtype',
900     });
901
902     # Create a biblio instance for testing
903     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
904     my $biblio = $builder->build_sample_biblio();
905
906     # Add an item.
907     my ($item_bibnum, $item_bibitemnum, $itemnumber) = AddItem({ homebranch => $library->{branchcode}, holdingbranch => $library->{branchcode}, location => $location, itype => $itemtype->{itemtype} } , $biblio->biblionumber);
908
909     # False means no logging
910     $schema->resultset('ActionLog')->search()->delete();
911     ModItem({ location => $location }, $biblio->biblionumber, $itemnumber, { log_action => 0 });
912     is( $schema->resultset('ActionLog')->count(), 0, 'False value does not trigger logging' );
913
914     # True means logging
915     $schema->resultset('ActionLog')->search()->delete();
916     ModItem({ location => $location }, $biblio->biblionumber, $itemnumber, { log_action => 1 });
917     is( $schema->resultset('ActionLog')->count(), 1, 'True value does trigger logging' );
918
919     # Undefined defaults to true
920     $schema->resultset('ActionLog')->search()->delete();
921     ModItem({ location => $location }, $biblio->biblionumber, $itemnumber);
922     is( $schema->resultset('ActionLog')->count(), 1, 'Undefined value defaults to true, triggers logging' );
923
924     $schema->storage->txn_rollback;
925 };
926
927 subtest 'Check stockrotationitem relationship' => sub {
928     plan tests => 1;
929
930     $schema->storage->txn_begin();
931
932     my $builder = t::lib::TestBuilder->new;
933     my $item = $builder->build({ source => 'Item' });
934
935     $builder->build({
936         source => 'Stockrotationitem',
937         value  => { itemnumber_id => $item->{itemnumber} }
938     });
939
940     my $sritem = Koha::Items->find($item->{itemnumber})->stockrotationitem;
941     isa_ok( $sritem, 'Koha::StockRotationItem', "Relationship works and correctly creates Koha::Object." );
942
943     $schema->storage->txn_rollback;
944 };
945
946 subtest 'Check add_to_rota method' => sub {
947     plan tests => 2;
948
949     $schema->storage->txn_begin();
950
951     my $builder = t::lib::TestBuilder->new;
952     my $item = $builder->build({ source => 'Item' });
953     my $rota = $builder->build({ source => 'Stockrotationrota' });
954     my $srrota = Koha::StockRotationRotas->find($rota->{rota_id});
955
956     $builder->build({
957         source => 'Stockrotationstage',
958         value  => { rota_id => $rota->{rota_id} },
959     });
960
961     my $sritem = Koha::Items->find($item->{itemnumber});
962     $sritem->add_to_rota($rota->{rota_id});
963
964     is(
965         Koha::StockRotationItems->find($item->{itemnumber})->stage_id,
966         $srrota->stockrotationstages->next->stage_id,
967         "Adding to a rota a new sritem item being assigned to its first stage."
968     );
969
970     my $newrota = $builder->build({ source => 'Stockrotationrota' });
971
972     my $srnewrota = Koha::StockRotationRotas->find($newrota->{rota_id});
973
974     $builder->build({
975         source => 'Stockrotationstage',
976         value  => { rota_id => $newrota->{rota_id} },
977     });
978
979     $sritem->add_to_rota($newrota->{rota_id});
980
981     is(
982         Koha::StockRotationItems->find($item->{itemnumber})->stage_id,
983         $srnewrota->stockrotationstages->next->stage_id,
984         "Moving an item results in that sritem being assigned to the new first stage."
985     );
986
987     $schema->storage->txn_rollback;
988 };
989
990 subtest 'Split subfields in Item2Marc (Bug 21774)' => sub {
991     plan tests => 3;
992     $schema->storage->txn_begin;
993
994     my $builder = t::lib::TestBuilder->new;
995     my $biblio = $builder->build({ source => 'Biblio', value => { frameworkcode => q{} } });
996     my $item = $builder->build({ source => 'Item', value => { biblionumber => $biblio->{biblionumber}, ccode => 'A|B' } });
997
998     Koha::MarcSubfieldStructures->search({ tagfield => '952', tagsubfield => '8' })->delete; # theoretical precaution
999     Koha::MarcSubfieldStructures->search({ kohafield => 'items.ccode' })->delete;
1000     my $mapping = Koha::MarcSubfieldStructure->new({ frameworkcode => q{}, tagfield => '952', tagsubfield => '8', kohafield => 'items.ccode' })->store;
1001
1002     # Start testing
1003     my $marc = C4::Items::Item2Marc( $item, $biblio->{biblionumber} );
1004     my @subs = $marc->subfield( $mapping->tagfield, $mapping->tagsubfield );
1005     is( @subs, 2, 'Expect two subfields' );
1006     is( $subs[0], 'A', 'First subfield matches' );
1007     is( $subs[1], 'B', 'Second subfield matches' );
1008
1009     $schema->storage->txn_rollback;
1010 };