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