Bug 30362: Fix GetSoonestRenewDate to really return soonest renew date
[koha.git] / t / db_dependent / Biblio.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
20 use Test::More tests => 19;
21 use Test::MockModule;
22 use Test::Warn;
23 use List::MoreUtils qw( uniq );
24 use MARC::Record;
25
26 use t::lib::Mocks qw( mock_preference );
27 use t::lib::TestBuilder;
28
29 use Koha::Database;
30 use Koha::Caches;
31 use Koha::MarcSubfieldStructures;
32
33 use C4::Linker::Default qw( get_link );
34
35 BEGIN {
36     use_ok('C4::Biblio', qw( AddBiblio GetMarcFromKohaField BiblioAutoLink GetMarcSubfieldStructure GetMarcSubfieldStructureFromKohaField LinkBibHeadingsToAuthorities GetBiblioData ModBiblio GetMarcISSN GetMarcControlnumber GetMarcISBN GetMarcPrice GetFrameworkCode GetMarcUrls IsMarcStructureInternal GetMarcStructure GetXmlBiblio DelBiblio ));
37 }
38
39 my $schema = Koha::Database->new->schema;
40 $schema->storage->txn_begin;
41 my $dbh = C4::Context->dbh;
42 Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
43
44 my $builder = t::lib::TestBuilder->new;
45
46 subtest 'AddBiblio' => sub {
47     plan tests => 9;
48
49     my $marcflavour = 'MARC21';
50     t::lib::Mocks::mock_preference( 'marcflavour', $marcflavour );
51
52     my ( $f, $sf ) = GetMarcFromKohaField('biblioitems.cn_item');
53     my $cn_item_field = MARC::Field->new( $f, ' ', ' ',
54         $sf => 'Thisisgoingtobetoomanycharactersforthe.cn_item.field' );
55     my $record = MARC::Record->new();
56     $record->append_fields($cn_item_field);
57
58     my $nb_biblios = Koha::Biblios->count;
59     my ( $biblionumber, $biblioitemnumber );
60     warnings_like { ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio( $record, '' ) }
61         [ qr/Data too long for column 'cn_item'/, qr/Data too long for column 'cn_item'/ ],
62         "expected warnings when adding too long cn_item";
63     is( $biblionumber, undef,
64         'AddBiblio returns undef for biblionumber if something went wrong' );
65     is( $biblioitemnumber, undef,
66         'AddBiblio returns undef for biblioitemnumber if something went wrong'
67     );
68     is( Koha::Biblios->count, $nb_biblios,
69         'No biblio should have been added if something went wrong' );
70
71     ( $f, $sf ) = GetMarcFromKohaField('biblioitems.lccn');
72     my $lccn_field = MARC::Field->new( $f, ' ', ' ',
73         $sf => 'ThisisNOTgoingtobetoomanycharactersfortheLCCNfield' );
74     $record = MARC::Record->new();
75     $record->append_fields($lccn_field);
76
77     warnings_like { ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio( $record, '' ) }
78         [],
79         "No warning expected when adding a long LCCN";
80     isnt( $biblionumber, undef,
81         'AddBiblio returns the biblionumber' );
82     isnt( $biblioitemnumber, undef,
83         'AddBiblio returns the biblioitemnumber'
84     );
85     is( Koha::Biblios->count, $nb_biblios + 1,
86         'The biblio should have been added if nothing went wrong' );
87
88     t::lib::Mocks::mock_preference( 'AutoLinkBiblios', $marcflavour );
89     t::lib::Mocks::mock_preference( 'AutoCreateAuthorities', $marcflavour );
90     t::lib::Mocks::mock_preference( 'autoControlNumber', "OFF" );
91
92     my $mock_biblio = Test::MockModule->new("C4::Biblio");
93     $mock_biblio->mock( BiblioAutoLink => sub {
94         my $record = shift;
95         my $frameworkcode = shift;
96         warn "My biblionumber is ".$record->subfield('999','c')." and my frameworkcode is $frameworkcode";
97     });
98     warning_like { $builder->build_sample_biblio(); }
99         qr/My biblionumber is \d+ and my frameworkcode is /, "The biblionumber is correctly passed to BiblioAutoLink";
100
101 };
102
103 subtest 'GetMarcSubfieldStructureFromKohaField' => sub {
104     plan tests => 25;
105
106     my @columns = qw(
107         tagfield tagsubfield liblibrarian libopac repeatable mandatory kohafield tab
108         authorised_value authtypecode value_builder isurl hidden frameworkcode
109         seealso link defaultvalue maxlength
110     );
111
112     # biblio.biblionumber must be mapped so this should return something
113     my $marc_subfield_structure = GetMarcSubfieldStructureFromKohaField('biblio.biblionumber');
114
115     ok(defined $marc_subfield_structure, "There is a result");
116     is(ref $marc_subfield_structure, "HASH", "Result is a hashref");
117     foreach my $col (@columns) {
118         ok(exists $marc_subfield_structure->{$col}, "Hashref contains key '$col'");
119     }
120     is($marc_subfield_structure->{kohafield}, 'biblio.biblionumber', "Result is the good result");
121     like($marc_subfield_structure->{tagfield}, qr/^\d{3}$/, "tagfield is a valid tagfield");
122
123     # Add a test for list context (BZ 10306)
124     my @results = GetMarcSubfieldStructureFromKohaField('biblio.biblionumber');
125     is( @results, 1, 'We expect only one mapping' );
126     is_deeply( $results[0], $marc_subfield_structure,
127         'The first entry should be the same hashref as we had before' );
128
129     # foo.bar does not exist so this should return undef
130     $marc_subfield_structure = GetMarcSubfieldStructureFromKohaField('foo.bar');
131     is($marc_subfield_structure, undef, "invalid kohafield returns undef");
132
133 };
134
135 subtest "GetMarcSubfieldStructure" => sub {
136     plan tests => 5;
137
138     # Add multiple Koha to Marc mappings
139     Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => '399', tagsubfield => [ 'a', 'b' ] })->delete;
140     Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '399', tagsubfield => 'a', kohafield => "mytable.nicepages" })->store;
141     Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '399', tagsubfield => 'b', kohafield => "mytable.nicepages" })->store;
142     Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
143     my $structure = C4::Biblio::GetMarcSubfieldStructure('');
144
145     is( @{ $structure->{"mytable.nicepages"} }, 2,
146         'GetMarcSubfieldStructure should return two entries for nicepages' );
147     is( $structure->{"mytable.nicepages"}->[0]->{tagfield}, '399',
148         'Check tagfield for first entry' );
149     is( $structure->{"mytable.nicepages"}->[0]->{tagsubfield}, 'a',
150         'Check tagsubfield for first entry' );
151     is( $structure->{"mytable.nicepages"}->[1]->{tagfield}, '399',
152         'Check tagfield for second entry' );
153     is( $structure->{"mytable.nicepages"}->[1]->{tagsubfield}, 'b',
154         'Check tagsubfield for second entry' );
155 };
156
157 subtest "GetMarcFromKohaField" => sub {
158     plan tests => 8;
159
160     #NOTE: We are building on data from the previous subtest
161     # With: field 399 / mytable.nicepages
162
163     # Check call in list context for multiple mappings
164     my @retval = C4::Biblio::GetMarcFromKohaField('mytable.nicepages');
165     is( @retval, 4, 'Should return two tags and subfields' );
166     is( $retval[0], '399', 'Check first tag' );
167     is( $retval[1], 'a', 'Check first subfield' );
168     is( $retval[2], '399', 'Check second tag' );
169     is( $retval[3], 'b', 'Check second subfield' );
170
171     # Check same call in scalar context
172     is( C4::Biblio::GetMarcFromKohaField('mytable.nicepages'), '399',
173         'GetMarcFromKohaField returns first tag in scalar context' );
174
175     # Bug 19096 Default is authoritative
176     # If we add a new empty framework, we should still get the mappings
177     # from Default. CAUTION: This test passes intentionally the obsoleted
178     # framework parameter.
179     my $new_fw = t::lib::TestBuilder->new->build({source => 'BiblioFramework'});
180     @retval = C4::Biblio::GetMarcFromKohaField(
181         'mytable.nicepages', $new_fw->{frameworkcode},
182     );
183     is( @retval, 4, 'Still got two pairs of tags/subfields' );
184     is( $retval[0].$retval[1], '399a', 'Including 399a' );
185 };
186
187 subtest "Authority creation with default linker" => sub {
188     plan tests => 4;
189     # Automatic authority creation
190     t::lib::Mocks::mock_preference('LinkerModule', 'Default');
191     t::lib::Mocks::mock_preference('AutoLinkBiblios', 1);
192     t::lib::Mocks::mock_preference('AutoCreateAuthorities', 1);
193     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
194     my $linker = C4::Linker::Default->new({});
195     my $authorities_mod = Test::MockModule->new( 'C4::Heading' );
196     $authorities_mod->mock(
197         'authorities',
198         sub {
199             my $results = [{ authid => 'original' },{ authid => 'duplicate' }];
200             return $results;
201         }
202     );
203     my $marc_record = MARC::Record->new();
204     my $field = MARC::Field->new(655, ' ', ' ','a' => 'Magical realism');
205     $marc_record->append_fields( $field );
206     my ($num_changed,$results) = LinkBibHeadingsToAuthorities($linker, $marc_record, "",undef);
207     is( $num_changed, 0, "We shouldn't link or create a new record");
208     ok( !defined $results->{added}, "If we have multiple matches, we shouldn't create a new record");
209
210     ($num_changed,$results) = LinkBibHeadingsToAuthorities($linker, $marc_record, "",undef);
211     is( $num_changed, 0, "We shouldn't link or create a new record using cached result");
212     ok( !defined $results->{added}, "If we have multiple matches, we shouldn't create a new record on second instance");
213 };
214
215
216
217 # Mocking variables
218 my $biblio_module = Test::MockModule->new('C4::Biblio');
219 $biblio_module->mock(
220     'GetMarcSubfieldStructure',
221     sub {
222         my ($self) = shift;
223
224         my ( $title_field,            $title_subfield )            = get_title_field();
225         my ( $subtitle_field,         $subtitle_subfield )         = get_subtitle_field();
226         my ( $medium_field,           $medium_subfield )           = get_medium_field();
227         my ( $part_number_field,      $part_number_subfield )      = get_part_number_field();
228         my ( $part_name_field,        $part_name_subfield )        = get_part_name_field();
229         my ( $isbn_field,             $isbn_subfield )             = get_isbn_field();
230         my ( $issn_field,             $issn_subfield )             = get_issn_field();
231         my ( $biblionumber_field,     $biblionumber_subfield )     = ( '999', 'c' );
232         my ( $biblioitemnumber_field, $biblioitemnumber_subfield ) = ( '999', '9' );
233         my ( $itemnumber_field,       $itemnumber_subfield )       = get_itemnumber_field();
234
235         return {
236             'biblio.title'                 => [ { tagfield => $title_field,            tagsubfield => $title_subfield } ],
237             'biblio.subtitle'              => [ { tagfield => $subtitle_field,         tagsubfield => $subtitle_subfield } ],
238             'biblio.medium'                => [ { tagfield => $medium_field,           tagsubfield => $medium_subfield } ],
239             'biblio.part_number'           => [ { tagfield => $part_number_field,      tagsubfield => $part_number_subfield } ],
240             'biblio.part_name'             => [ { tagfield => $part_name_field,        tagsubfield => $part_name_subfield } ],
241             'biblio.biblionumber'          => [ { tagfield => $biblionumber_field,     tagsubfield => $biblionumber_subfield } ],
242             'biblioitems.isbn'             => [ { tagfield => $isbn_field,             tagsubfield => $isbn_subfield } ],
243             'biblioitems.issn'             => [ { tagfield => $issn_field,             tagsubfield => $issn_subfield } ],
244             'biblioitems.biblioitemnumber' => [ { tagfield => $biblioitemnumber_field, tagsubfield => $biblioitemnumber_subfield } ],
245             'items.itemnumber'             => [ { tagfield => $itemnumber_subfield,    tagsubfield => $itemnumber_subfield } ],
246         };
247       }
248 );
249
250 my $currency = Test::MockModule->new('Koha::Acquisition::Currencies');
251 $currency->mock(
252     'get_active',
253     sub {
254         return Koha::Acquisition::Currency->new(
255             {   symbol   => '$',
256                 isocode  => 'USD',
257                 currency => 'USD',
258                 active   => 1,
259             }
260         );
261     }
262 );
263
264 sub run_tests {
265
266     my $marcflavour = shift;
267     t::lib::Mocks::mock_preference('marcflavour', $marcflavour);
268     # Authority tests don't interact well with Elasticsearch at the moment due to the fact that there's currently no way to
269     # roll back ES index changes.
270     t::lib::Mocks::mock_preference('SearchEngine', 'Zebra');
271     t::lib::Mocks::mock_preference('autoControlNumber', 'OFF');
272
273     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
274
275     my $isbn = '0590353403';
276     my $title = 'Foundation';
277     my $subtitle1 = 'Research';
278     my $subtitle2 = 'Conclusions';
279     my $medium = 'Medium';
280     my $part_number = '123';
281     my $part_name = 'First years';
282
283     # Generate a record with just the ISBN
284     my $marc_record = MARC::Record->new;
285     $marc_record->append_fields( create_isbn_field( $isbn, $marcflavour ) );
286
287     # Add the record to the DB
288     my( $biblionumber, $biblioitemnumber ) = AddBiblio( $marc_record, '' );
289     my $data = GetBiblioData( $biblionumber );
290     is( $data->{ isbn }, $isbn,
291         '(GetBiblioData) ISBN correctly retireved.');
292     is( $data->{ title }, undef,
293         '(GetBiblioData) Title field is empty in fresh biblio.');
294
295     my $biblio = Koha::Biblios->find($biblionumber);
296
297     my ( $isbn_field, $isbn_subfield ) = get_isbn_field();
298     my $marc = $biblio->metadata->record;
299     is( $marc->subfield( $isbn_field, $isbn_subfield ), $isbn, );
300
301     # Add title
302     my $field = create_title_field( $title, $marcflavour );
303     $marc_record->append_fields( $field );
304     ModBiblio( $marc_record, $biblionumber ,'' );
305     $data = GetBiblioData( $biblionumber );
306     is( $data->{ title }, $title,
307         'ModBiblio correctly added the title field, and GetBiblioData.');
308     is( $data->{ isbn }, $isbn, '(ModBiblio) ISBN is still there after ModBiblio.');
309     $marc = $biblio->get_from_storage->metadata->record;
310     my ( $title_field, $title_subfield ) = get_title_field();
311     is( $marc->subfield( $title_field, $title_subfield ), $title, );
312
313     # Add other fields
314     $marc_record->append_fields( create_field( $subtitle1, $marcflavour, get_subtitle_field() ) );
315     $marc_record->append_fields( create_field( $subtitle2, $marcflavour, get_subtitle_field() ) );
316     $marc_record->append_fields( create_field( $medium, $marcflavour, get_medium_field() ) );
317     $marc_record->append_fields( create_field( $part_number, $marcflavour, get_part_number_field() ) );
318     $marc_record->append_fields( create_field( $part_name, $marcflavour, get_part_name_field() ) );
319
320     ModBiblio( $marc_record, $biblionumber ,'' );
321     $data = GetBiblioData( $biblionumber );
322     is( $data->{ title }, $title, '(ModBiblio) still there after adding other fields.' );
323     is( $data->{ isbn }, $isbn, '(ModBiblio) ISBN is still there after adding other fields.' );
324
325     is( $data->{ subtitle }, "$subtitle1 | $subtitle2", '(ModBiblio) subtitles correctly added and returned in GetBiblioData.' );
326     is( $data->{ medium }, $medium, '(ModBiblio) medium correctly added and returned in GetBiblioData.' );
327     is( $data->{ part_number }, $part_number, '(ModBiblio) part_number correctly added and returned in GetBiblioData.' );
328     is( $data->{ part_name }, $part_name, '(ModBiblio) part_name correctly added and returned in GetBiblioData.' );
329
330     my $biblioitem = Koha::Biblioitems->find( $biblioitemnumber );
331     is( $biblioitem->_result->biblio->title, $title, # Should be $biblioitem->biblio instead, but not needed elsewhere for now
332         'Do not know if this makes sense - compare result of previous two GetBiblioData tests.');
333     is( $biblioitem->isbn, $isbn,
334         'Second test checking it returns the correct isbn.');
335
336     my $success = 0;
337     $field = MARC::Field->new(
338             655, ' ', ' ',
339             'a' => 'Auction catalogs',
340             '9' => '1'
341             );
342     eval {
343         $marc_record->append_fields($field);
344         $success = ModBiblio($marc_record,$biblionumber,'');
345     } or do {
346         diag($@);
347         $success = 0;
348     };
349     ok($success, "ModBiblio handles authority-linked 655");
350
351     eval {
352         $field->delete_subfields('a');
353         $marc_record->append_fields($field);
354         $success = ModBiblio($marc_record,$biblionumber,'');
355     } or do {
356         diag($@);
357         $success = 0;
358     };
359     ok($success, "ModBiblio handles 655 with authority link but no heading");
360
361     eval {
362         $field->delete_subfields('9');
363         $marc_record->append_fields($field);
364         $success = ModBiblio($marc_record,$biblionumber,'');
365     } or do {
366         diag($@);
367         $success = 0;
368     };
369     ok($success, "ModBiblio handles 655 with no subfields");
370
371     ## Testing GetMarcISSN
372     my $issns;
373     $issns = GetMarcISSN( $marc_record, $marcflavour );
374     is( $issns->[0], undef,
375         'GetMarcISSN handles records without the ISSN field (list is empty)' );
376     is( scalar @$issns, 0,
377         'GetMarcISSN handles records without the ISSN field (count is 0)' );
378     # Add an ISSN field
379     my $issn = '1234-1234';
380     $field = create_issn_field( $issn, $marcflavour );
381     $marc_record->append_fields($field);
382     $issns = GetMarcISSN( $marc_record, $marcflavour );
383     is( $issns->[0], $issn,
384         'GetMarcISSN handles records with a single ISSN field (first element is correct)' );
385     is( scalar @$issns, 1,
386         'GetMARCISSN handles records with a single ISSN field (count is 1)');
387     # Add multiple ISSN field
388     my @more_issns = qw/1111-1111 2222-2222 3333-3333/;
389     foreach (@more_issns) {
390         $field = create_issn_field( $_, $marcflavour );
391         $marc_record->append_fields($field);
392     }
393     $issns = GetMarcISSN( $marc_record, $marcflavour );
394     is( scalar @$issns, 4,
395         'GetMARCISSN handles records with multiple ISSN fields (count correct)');
396     # Create an empty ISSN
397     $field = create_issn_field( "", $marcflavour );
398     $marc_record->append_fields($field);
399     $issns = GetMarcISSN( $marc_record, $marcflavour );
400     is( scalar @$issns, 4,
401         'GetMARCISSN skips empty ISSN fields (Bug 12674)');
402
403     ## Testing GetMarcControlnumber
404     my $controlnumber;
405     $controlnumber = GetMarcControlnumber( $marc_record, $marcflavour );
406     is( $controlnumber, '', 'GetMarcControlnumber handles records without 001' );
407
408     $field = MARC::Field->new( '001', '' );
409     $marc_record->append_fields($field);
410     $controlnumber = GetMarcControlnumber( $marc_record, $marcflavour );
411     is( $controlnumber, '', 'GetMarcControlnumber handles records with empty 001' );
412
413     $field = $marc_record->field('001');
414     $field->update('123456789X');
415     $controlnumber = GetMarcControlnumber( $marc_record, $marcflavour );
416     is( $controlnumber, '123456789X', 'GetMarcControlnumber handles records with 001' );
417
418     ## Testing GetMarcISBN
419     my $record_for_isbn = MARC::Record->new();
420     my $isbns = GetMarcISBN( $record_for_isbn, $marcflavour );
421     is( scalar @$isbns, 0, '(GetMarcISBN) The record contains no ISBN');
422
423     # We add one ISBN
424     $isbn_field = create_isbn_field( $isbn, $marcflavour );
425     $record_for_isbn->append_fields( $isbn_field );
426     $isbns = GetMarcISBN( $record_for_isbn, $marcflavour );
427     is( scalar @$isbns, 1, '(GetMarcISBN) The record contains one ISBN');
428     is( $isbns->[0], $isbn, '(GetMarcISBN) The record contains our ISBN');
429
430     # We add 3 more ISBNs
431     $record_for_isbn = MARC::Record->new();
432     my @more_isbns = qw/1111111111 2222222222 3333333333 444444444/;
433     foreach (@more_isbns) {
434         $field = create_isbn_field( $_, $marcflavour );
435         $record_for_isbn->append_fields($field);
436     }
437     $isbns = GetMarcISBN( $record_for_isbn, $marcflavour );
438     is( scalar @$isbns, 4, '(GetMarcISBN) The record contains 4 ISBNs');
439     for my $i (0 .. $#more_isbns) {
440         is( $isbns->[$i], $more_isbns[$i],
441             "(GetMarcISBN) Correctly retrieves ISBN #". ($i + 1));
442     }
443
444     is( GetMarcPrice( $record_for_isbn, $marcflavour ), 100,
445         "GetMarcPrice returns the correct value");
446     my $frameworkcode = GetFrameworkCode($biblionumber);
447     my $updatedrecord = $biblio->metadata->record;
448     my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField( "biblioitems.biblioitemnumber" );
449     die qq{No biblioitemnumber tag for framework "$frameworkcode"} unless $biblioitem_tag;
450     my $biblioitemnumbertotest;
451     if ( $biblioitem_tag < 10 ) {
452         $biblioitemnumbertotest = $updatedrecord->field($biblioitem_tag)->data();
453     } else {
454         $biblioitemnumbertotest = $updatedrecord->field($biblioitem_tag)->subfield($biblioitem_subfield);
455     }
456
457     # test for GetMarcUrls
458     $marc_record->append_fields(
459         MARC::Field->new( '856', '', '', u => ' https://koha-community.org ' ),
460         MARC::Field->new( '856', '', '', u => 'koha-community.org' ),
461     );
462     my $marcurl = GetMarcUrls( $marc_record, $marcflavour );
463     is( @$marcurl, 2, 'GetMarcUrls returns two URLs' );
464     like( $marcurl->[0]->{MARCURL}, qr/^https/, 'GetMarcUrls did not stumble over a preceding space' );
465     ok( $marcflavour ne 'MARC21' || $marcurl->[1]->{MARCURL} =~ /^http:\/\//,
466         'GetMarcUrls prefixed a MARC21 URL with http://' );
467
468     # Automatic authority creation
469     t::lib::Mocks::mock_preference('AutoLinkBiblios', 1);
470     t::lib::Mocks::mock_preference('AutoCreateAuthorities', 1);
471     my $authorities_mod = Test::MockModule->new( 'C4::Heading' );
472     $authorities_mod->mock(
473         'authorities',
474         sub {
475             my @results;
476             return \@results;
477         }
478     );
479     $success = 0;
480     $field = create_author_field('Author Name');
481     eval {
482         $marc_record->append_fields($field);
483         $success = ModBiblio($marc_record,$biblionumber,'');
484     } or do {
485         diag($@);
486         $success = 0;
487     };
488     ok($success, "ModBiblio handles authority addition for author");
489
490     my ($author_field, $author_subfield, $author_relator_subfield) = get_author_field();
491     $field = $marc_record->field($author_field);
492     ok($field->subfield($author_subfield), "ModBiblio keeps $author_field$author_subfield intact");
493
494     my $authid = $field->subfield('9');
495     ok($authid, 'ModBiblio adds authority id');
496
497     use_ok('C4::AuthoritiesMarc', qw( GetAuthority ));
498     my $auth_record = C4::AuthoritiesMarc::GetAuthority($authid);
499     ok($auth_record, 'Authority record successfully retrieved');
500
501
502     my ($auth_author_field, $auth_author_subfield) = get_auth_author_field();
503     $field = $auth_record->field($auth_author_field);
504     ok($field, "Authority record contains field $auth_author_field");
505     is(
506         $field->subfield($auth_author_subfield),
507         'Author Name',
508         'Authority $auth_author_field$auth_author_subfield contains author name'
509     );
510     is($field->subfield($author_relator_subfield), undef, 'Authority does not contain relator subfield');
511
512     # Reset settings
513     t::lib::Mocks::mock_preference('AutoLinkBiblios', 0);
514     t::lib::Mocks::mock_preference('AutoCreateAuthorities', 0);
515 }
516
517 sub get_title_field {
518     my $marc_flavour = C4::Context->preference('marcflavour');
519     return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'a' ) : ( '245', 'a' );
520 }
521
522 sub get_medium_field {
523     my $marc_flavour = C4::Context->preference('marcflavour');
524     return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'b' ) : ( '245', 'h' );
525 }
526
527 sub get_subtitle_field {
528     my $marc_flavour = C4::Context->preference('marcflavour');
529     return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'e' ) : ( '245', 'b' );
530 }
531
532 sub get_part_number_field {
533     my $marc_flavour = C4::Context->preference('marcflavour');
534     return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'h' ) : ( '245', 'n' );
535 }
536
537 sub get_part_name_field {
538     my $marc_flavour = C4::Context->preference('marcflavour');
539     return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'i' ) : ( '245', 'p' );
540 }
541
542 sub get_isbn_field {
543     my $marc_flavour = C4::Context->preference('marcflavour');
544     return ( $marc_flavour eq 'UNIMARC' ) ? ( '010', 'a' ) : ( '020', 'a' );
545 }
546
547 sub get_issn_field {
548     my $marc_flavour = C4::Context->preference('marcflavour');
549     return ( $marc_flavour eq 'UNIMARC' ) ? ( '011', 'a' ) : ( '022', 'a' );
550 }
551
552 sub get_itemnumber_field {
553     my $marc_flavour = C4::Context->preference('marcflavour');
554     return ( $marc_flavour eq 'UNIMARC' ) ? ( '995', '9' ) : ( '952', '9' );
555 }
556
557 sub get_author_field {
558     my $marc_flavour = C4::Context->preference('marcflavour');
559     return ( $marc_flavour eq 'UNIMARC' ) ? ( '700', 'a', '4' ) : ( '100', 'a', 'e' );
560 }
561
562 sub get_auth_author_field {
563     my $marc_flavour = C4::Context->preference('marcflavour');
564     return ( $marc_flavour eq 'UNIMARC' ) ? ( '106', 'a' ) : ( '100', 'a' );
565 }
566
567 sub create_title_field {
568     my ( $title, $marcflavour ) = @_;
569
570     my ( $title_field, $title_subfield ) = get_title_field();
571     my $field = MARC::Field->new( $title_field, '', '', $title_subfield => $title );
572
573     return $field;
574 }
575
576 sub create_field {
577     my ( $content, $marcflavour, $field, $subfield ) = @_;
578
579     return MARC::Field->new( $field, '', '', $subfield => $content );
580 }
581
582 sub create_isbn_field {
583     my ( $isbn, $marcflavour ) = @_;
584
585     my ( $isbn_field, $isbn_subfield ) = get_isbn_field();
586     my $field = MARC::Field->new( $isbn_field, '', '', $isbn_subfield => $isbn );
587
588     # Add the price subfield
589     my $price_subfield = ( $marcflavour eq 'UNIMARC' ) ? 'd' : 'c';
590     $field->add_subfields( $price_subfield => '$100' );
591
592     return $field;
593 }
594
595 sub create_issn_field {
596     my ( $issn, $marcflavour ) = @_;
597
598     my ( $issn_field, $issn_subfield ) = get_issn_field();
599     my $field = MARC::Field->new( $issn_field, '', '', $issn_subfield => $issn );
600
601     return $field;
602 }
603
604 sub create_author_field {
605     my ( $author ) = @_;
606
607     my ( $author_field, $author_subfield, $author_relator_subfield ) = get_author_field();
608     my $field = MARC::Field->new(
609         $author_field, '', '',
610         $author_subfield => $author,
611         $author_relator_subfield => 'aut'
612     );
613
614     return $field;
615 }
616
617 subtest 'MARC21' => sub {
618     plan tests => 46;
619     run_tests('MARC21');
620     $schema->storage->txn_rollback;
621     $schema->storage->txn_begin;
622 };
623
624 subtest 'UNIMARC' => sub {
625     plan tests => 46;
626
627     # Mock the auth type data for UNIMARC
628     $dbh->do("UPDATE auth_types SET auth_tag_to_report = '106' WHERE auth_tag_to_report = '100'") or die $dbh->errstr;
629
630     run_tests('UNIMARC');
631     $schema->storage->txn_rollback;
632     $schema->storage->txn_begin;
633 };
634
635 subtest 'IsMarcStructureInternal' => sub {
636     plan tests => 9;
637     my $tagslib = GetMarcStructure();
638     my @internals;
639     for my $tag ( sort keys %$tagslib ) {
640         next unless $tag;
641         for my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
642             push @internals, $subfield if IsMarcStructureInternal($tagslib->{$tag}{$subfield});
643         }
644     }
645     @internals = uniq @internals;
646     is( scalar(@internals), 7, 'expect 7 internals');
647     is( grep( /^lib$/, @internals ), 1, 'check lib' );
648     is( grep( /^tab$/, @internals ), 1, 'check tab' );
649     is( grep( /^mandatory$/, @internals ), 1, 'check mandatory' );
650     is( grep( /^repeatable$/, @internals ), 1, 'check repeatable' );
651     is( grep( /^important$/, @internals ), 1, 'check important' );
652     is( grep( /^a$/, @internals ), 0, 'no subfield a' );
653     is( grep( /^ind1_defaultvalue$/, @internals ), 1, 'check indicator 1 default value' );
654     is( grep( /^ind2_defaultvalue$/, @internals ), 1, 'check indicator 2 default value' );
655 };
656
657 subtest 'deletedbiblio_metadata' => sub {
658     plan tests => 2;
659
660     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
661
662     my ($biblionumber, $biblioitemnumber) = AddBiblio(MARC::Record->new, '');
663     my $biblio_metadata = C4::Biblio::GetXmlBiblio( $biblionumber );
664     C4::Biblio::DelBiblio( $biblionumber );
665     my ( $moved ) = $dbh->selectrow_array(q|SELECT biblionumber FROM deletedbiblio WHERE biblionumber=?|, undef, $biblionumber);
666     is( $moved, $biblionumber, 'Found in deletedbiblio' );
667     ( $moved ) = $dbh->selectrow_array(q|SELECT biblionumber FROM deletedbiblio_metadata WHERE biblionumber=?|, undef, $biblionumber);
668     is( $moved, $biblionumber, 'Found in deletedbiblio_metadata' );
669 };
670
671 subtest 'DelBiblio' => sub {
672
673     plan tests => 10;
674
675     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
676
677     my ($biblionumber, $biblioitemnumber) = C4::Biblio::AddBiblio(MARC::Record->new, '');
678     my $deleted = C4::Biblio::DelBiblio( $biblionumber );
679     is( $deleted, undef, 'DelBiblio returns undef is the biblio has been deleted correctly - Must be 1 instead'); # FIXME We should return 1 instead!
680
681     $deleted = C4::Biblio::DelBiblio( $biblionumber );
682     is( $deleted, undef, 'DelBiblo should return undef is the record did not exist');
683
684     my $biblio       = $builder->build_sample_biblio;
685     my $subscription = $builder->build_object(
686         {
687             class => 'Koha::Subscriptions',
688             value => { biblionumber => $biblio->biblionumber }
689         }
690     );
691     my $serial = $builder->build_object(
692         {
693             class => 'Koha::Serials',
694             value => {
695                 biblionumber   => $biblio->biblionumber,
696                 subscriptionid => $subscription->subscriptionid
697             }
698         }
699     );
700     my $subscription_history = $builder->build_object(
701         {
702             class => 'Koha::Subscription::Histories',
703             value => {
704                 biblionumber   => $biblio->biblionumber,
705                 subscriptionid => $subscription->subscriptionid
706             }
707         }
708     );
709
710     my $order_basket = $builder->build( { source => 'Aqbasket' } );
711
712     my $orderinfo = {
713         biblionumber => $biblio->biblionumber,
714         basketno     => $order_basket->{basketno},
715     };
716     my $order = $builder->build_object(
717         { class => 'Koha::Acquisition::Orders', value => $orderinfo } );
718
719     # Add some ILL requests
720     my $ill_req_1 = $builder->build_object({ class => 'Koha::Illrequests', value => { biblio_id => $biblio->id, deleted_biblio_id => undef } });
721     my $ill_req_2 = $builder->build_object({ class => 'Koha::Illrequests', value => { biblio_id => $biblio->id, deleted_biblio_id => undef } });
722
723     C4::Biblio::DelBiblio($biblio->biblionumber); # Or $biblio->delete
724     is( $subscription->get_from_storage, undef, 'subscription should be deleted on biblio deletion' );
725     is( $serial->get_from_storage, undef, 'serial should be deleted on biblio deletion' );
726     is( $subscription_history->get_from_storage, undef, 'subscription history should be deleted on biblio deletion' );
727     is( $order->get_from_storage->deleted_biblionumber, $biblio->biblionumber, 'biblionumber of order has been moved to deleted_biblionumber column' );
728
729     $ill_req_1 = $ill_req_1->get_from_storage;
730     $ill_req_2 = $ill_req_2->get_from_storage;
731     is( $ill_req_1->biblio_id, undef, 'biblio_id cleared on biblio deletion' );
732     is( $ill_req_1->deleted_biblio_id, $biblio->id, 'biblio_id is kept on the deleted_biblio_id column' );
733     is( $ill_req_2->biblio_id, undef, 'biblio_id cleared on biblio deletion' );
734     is( $ill_req_2->deleted_biblio_id, $biblio->id, 'biblio_id is kept on the deleted_biblio_id column' );
735 };
736
737 subtest 'MarcFieldForCreatorAndModifier' => sub {
738     plan tests => 8;
739
740     t::lib::Mocks::mock_preference('MarcFieldForCreatorId', '998$a');
741     t::lib::Mocks::mock_preference('MarcFieldForCreatorName', '998$b');
742     t::lib::Mocks::mock_preference('MarcFieldForModifierId', '998$c');
743     t::lib::Mocks::mock_preference('MarcFieldForModifierName', '998$d');
744     my $c4_context = Test::MockModule->new('C4::Context');
745     $c4_context->mock('userenv', sub { return { number => 123, firstname => 'John', surname => 'Doe'}; });
746
747     my $record = MARC::Record->new();
748     my ($biblionumber) = C4::Biblio::AddBiblio($record, '');
749
750     my $biblio = Koha::Biblios->find($biblionumber);
751     $record = $biblio->metadata->record;
752     is($record->subfield('998', 'a'), 123, '998$a = 123');
753     is($record->subfield('998', 'b'), 'John Doe', '998$b = John Doe');
754     is($record->subfield('998', 'c'), 123, '998$c = 123');
755     is($record->subfield('998', 'd'), 'John Doe', '998$d = John Doe');
756
757     $c4_context->mock('userenv', sub { return { number => 321, firstname => 'Jane', surname => 'Doe'}; });
758     C4::Biblio::ModBiblio($record, $biblionumber, '');
759
760     $record = $biblio->get_from_storage->metadata->record;
761     is($record->subfield('998', 'a'), 123, '998$a = 123');
762     is($record->subfield('998', 'b'), 'John Doe', '998$b = John Doe');
763     is($record->subfield('998', 'c'), 321, '998$c = 321');
764     is($record->subfield('998', 'd'), 'Jane Doe', '998$d = Jane Doe');
765 };
766
767 subtest 'ModBiblio called from linker test' => sub {
768     plan tests => 2;
769     my $called = 0;
770     t::lib::Mocks::mock_preference('AutoLinkBiblios', 1);
771     my $biblio_mod = Test::MockModule->new( 'C4::Biblio' );
772     $biblio_mod->mock( 'LinkBibHeadingsToAuthorities', sub {
773         $called = 1;
774     });
775     my $record = MARC::Record->new();
776     my ($biblionumber) = C4::Biblio::AddBiblio($record,'');
777     C4::Biblio::ModBiblio($record,$biblionumber,'');
778     is($called,1,"We called to link bibs because not from linker");
779     $called = 0;
780     C4::Biblio::ModBiblio($record,$biblionumber,'',{ disable_autolink => 1 });
781     is($called,0,"We didn't call to link bibs because from linker");
782 };
783
784 subtest "LinkBibHeadingsToAuthorities tests" => sub {
785     plan tests => 5;
786
787     # Set up mocks to return more than 1 match
788     my $biblio_mod = Test::MockModule->new( 'C4::Linker::Default' );
789     $biblio_mod->mock( 'get_link', sub {
790         return (undef, undef, 2);
791     });
792     # UNIMARC return values should be consistent with MARC21
793     # testing with MARC21 should be sufficient for now
794     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
795     t::lib::Mocks::mock_preference('AutoCreateAuthorities', '0');
796
797     my $linker = C4::Linker::Default->new();
798     my $biblio = $builder->build_sample_biblio();
799     my $record = $biblio->metadata->record;
800
801     # Generate a field, no current link
802     my $field = MARC::Field->new('650','','','a' => 'Duplicated' );
803
804     $record->append_fields($field);
805     my ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities( $linker, $record, "", undef, 650, 1 );
806     is( $num_headings_changed, 0, 'We did not make any changes because we found 2' );
807     is_deeply( $results->{unlinked},
808         {"Duplicated" => 1 },
809         "The heading was not linked"
810     );
811     is_deeply( $results->{details}[0],
812         {
813             tag => 650,
814             authid => undef,
815             status => 'MULTIPLE_MATCH',
816             auth_type => 'TOPIC_TERM',
817             tag_to_report => 150
818         },
819         "The heading was not linked"
820     );
821
822     t::lib::Mocks::mock_preference('AutoCreateAuthorities', '1');
823     ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities( $linker, $record, "", undef, 650, 1 );
824     is( $num_headings_changed, 0, 'We did not make any changes because we found 2' );
825     is_deeply( $results->{details}[0],
826         {
827             tag => 650,
828             authid => undef,
829             status => 'MULTIPLE_MATCH',
830             auth_type => 'TOPIC_TERM',
831             tag_to_report => 150
832         },
833         "When AutoCreateAuthorities is enabled, multiple results are reported"
834     );
835
836 };
837
838 subtest "LinkBibHeadingsToAuthorities record generation tests" => sub {
839     plan tests => 12;
840
841     # Set up mocks to ensure authorities are generated
842     my $biblio_mod = Test::MockModule->new( 'C4::Linker::Default' );
843     $biblio_mod->mock( 'get_link', sub {
844         return (undef,undef);
845     });
846     # UNIMARC valid headings are built from the marc_subfield_structure for bibs and
847     # include all subfields as valid, testing with MARC21 should be sufficient for now
848     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
849     t::lib::Mocks::mock_preference('AutoCreateAuthorities', '1');
850
851     my $linker = C4::Linker::Default->new();
852     my $biblio = $builder->build_sample_biblio();
853     my $record = $biblio->metadata->record;
854
855     # Generate a record including all valid subfields and an invalid one 'e'
856     my $field = MARC::Field->new('650','','','a' => 'Beach city', 'b' => 'Weirdness', 'v' => 'Fiction', 'x' => 'Books', 'y' => '21st Century', 'z' => 'Fish Stew Pizza', 'e' => 'Depicted');
857
858     $record->append_fields($field);
859     my ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities($linker, $record, "",undef,650);
860
861     is( $num_headings_changed, 1, 'We changed the one we passed' );
862     is_deeply( $results->{added},
863         {"Beach city Weirdness--Fiction--Books--21st Century--Fish Stew Pizza" => 1 },
864         "We added an authority record for the heading"
865     );
866
867     # Now we check the authority record itself
868     my $authority = GetAuthority( $record->subfield('650','9') );
869     is( $authority->field('150')->as_string(),
870         "Beach city Weirdness Fiction Books 21st Century Fish Stew Pizza",
871         "The generated record contains the correct subfields"
872     );
873
874     #Add test for this case using verbose
875     $record->field('650')->delete_subfield('9');
876     ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities($linker, $record, "",undef, 650, 1);
877     is( $num_headings_changed, 1, 'We changed the one we passed' );
878     is( $results->{details}->[0]->{status}, 'CREATED', "We added an authority record for the heading using verbose");
879
880     # Now we check the authority record itself
881     $authority = GetAuthority($results->{details}->[0]->{authid});
882
883     is( $authority->field('150')->as_string(),
884          "Beach city Weirdness Fiction Books 21st Century Fish Stew Pizza",
885          "The generated record contains the correct subfields when using verbose"
886     );
887
888     # Example series link with volume and punctuation
889     $field = MARC::Field->new('800','','','a' => 'Tolkien, J. R. R.', 'q' => '(John Ronald Reuel),', 'd' => '1892-1973.', 't' => 'Lord of the rings ;', 'v' => '1');
890     $record->append_fields($field);
891
892     ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities($linker, $record, "",undef, 800);
893
894     is( $num_headings_changed, 1, 'We changed the one we passed' );
895     is_deeply( $results->{added},
896         {"Tolkien, J. R. R. (John Ronald Reuel), 1892-1973. Lord of the rings ;" => 1 },
897         "We added an authority record for the heading"
898     );
899
900     # Now we check the authority record itself
901     $authority = GetAuthority( $record->subfield('800','9') );
902     is( $authority->field('100')->as_string(),
903         "Tolkien, J. R. R. (John Ronald Reuel), 1892-1973. Lord of the rings",
904         "The generated record contains the correct subfields"
905     );
906
907     # The same example With verbose
908     $record->field('800')->delete_subfield('9');
909     ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities($linker, $record, "",undef, 800, 1);
910     is( $num_headings_changed, 1, 'We changed the one we passed' );
911     is( $results->{details}->[0]->{status}, 'CREATED', "We added an authority record for the heading using verbose");
912
913     # Now we check the authority record itself
914     $authority = GetAuthority($results->{details}->[0]->{authid});
915     is( $authority->field('100')->as_string(),
916          "Tolkien, J. R. R. (John Ronald Reuel), 1892-1973. Lord of the rings",
917          "The generated record contains the correct subfields"
918     );
919 };
920
921 subtest 'autoControlNumber tests' => sub {
922
923     plan tests => 3;
924
925     t::lib::Mocks::mock_preference('autoControlNumber', 'OFF');
926
927     my $record = MARC::Record->new();
928     my ($biblio_id) = C4::Biblio::AddBiblio($record, '');
929     my $biblio = Koha::Biblios->find($biblio_id);
930
931     $record = $biblio->metadata->record;
932     is($record->field('001'), undef, '001 not set when pref is off');
933
934     t::lib::Mocks::mock_preference('autoControlNumber', 'biblionumber');
935     C4::Biblio::ModBiblio($record, $biblio_id, "", { skip_record_index => 1, disable_autolink => 1 });
936     $biblio->discard_changes;
937     $record = $biblio->metadata->record;
938     is($record->field('001')->as_string(), $biblio_id, '001 set to biblionumber when pref set and field is blank');
939
940     $record->field('001')->update('Not biblionumber');
941     C4::Biblio::ModBiblio($record, $biblio_id, "", { skip_record_index => 1, disable_autolink => 1 });
942     $biblio->discard_changes;
943     $record = $biblio->metadata->record;
944     is($record->field('001')->as_string(), 'Not biblionumber', '001 not set to biblionumber when pref set and field exists');
945
946 };
947
948 subtest 'record test' => sub {
949     plan tests => 1;
950
951     my $marc_record = MARC::Record->new;
952     $marc_record->append_fields( create_isbn_field( '0590353403', 'MARC21' ) );
953
954     my ($biblionumber) = C4::Biblio::AddBiblio( $marc_record, '' );
955
956     my $biblio = Koha::Biblios->find($biblionumber);
957
958     is( $biblio->record->as_formatted,
959         $biblio->metadata->record->as_formatted );
960 };
961
962 subtest 'record_schema test' => sub {
963     plan tests => 1;
964
965     my $marc_record = MARC::Record->new;
966     $marc_record->append_fields( create_isbn_field( '0590353403', 'MARC21' ) );
967
968     my ($biblionumber) = C4::Biblio::AddBiblio( $marc_record, '' );
969
970     my $biblio = Koha::Biblios->find($biblionumber);
971
972     is( $biblio->record_schema,
973         $biblio->metadata->schema );
974 };
975
976
977 subtest 'GetFrameworkCode' => sub {
978     plan tests => 4;
979
980     my $biblio = $builder->build_sample_biblio({ frameworkcode => 'OBP' });
981
982     is(GetFrameworkCode($biblio->biblionumber), 'OBP', 'GetFrameworkCode returns correct frameworkcode');
983
984     my $cache = Koha::Cache::Memory::Lite->get_instance();
985     my $cache_key = "FrameworkCode-" . $biblio->biblionumber;
986     my $frameworkcode = $cache->get_from_cache($cache_key);
987     is($frameworkcode, 'OBP', 'Cache has been set in GetFrameworkCode');
988
989     # Set new value directly in cache to make sure it's actually being used
990     $cache->set_in_cache($cache_key, 'OD');
991     is(GetFrameworkCode($biblio->biblionumber), 'OD', 'GetFrameworkCode returns correct frameworkcode, using cache');
992
993     # Test cache invalidation
994     ModBiblio($biblio->metadata->record, $biblio->biblionumber, 'OGR');
995     is(GetFrameworkCode($biblio->biblionumber), 'OGR', 'GetFrameworkCode returns correct frameworkcode after setting a new one though ModBiblio');
996
997 };
998
999 # Cleanup
1000 Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
1001 $schema->storage->txn_rollback;