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