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