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