-
Notifications
You must be signed in to change notification settings - Fork 257
/
ImportBatch.pm
1789 lines (1419 loc) · 59 KB
/
ImportBatch.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package C4::ImportBatch;
# Copyright (C) 2007 LibLime, 2012 C & P Bibliography Services
#
# This file is part of Koha.
#
# Koha is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# Koha is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Koha; if not, see <http://www.gnu.org/licenses>.
use strict;
use warnings;
use C4::Context;
use C4::Koha qw( GetNormalizedISBN );
use C4::Biblio qw(
AddBiblio
DelBiblio
GetMarcFromKohaField
GetXmlBiblio
ModBiblio
TransformMarcToKoha
);
use C4::Items qw( AddItemFromMarc ModItemFromMarc );
use C4::Charset qw( MarcToUTF8Record SetUTF8Flag StripNonXmlChars );
use C4::AuthoritiesMarc qw( AddAuthority GuessAuthTypeCode GetAuthorityXML ModAuthority DelAuthority GetAuthorizedHeading );
use C4::MarcModificationTemplates qw( ModifyRecordWithTemplate );
use Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue;
use Koha::Items;
use Koha::SearchEngine;
use Koha::SearchEngine::Indexer;
use Koha::Plugins::Handler;
use Koha::Logger;
our (@ISA, @EXPORT_OK);
BEGIN {
require Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(
GetZ3950BatchId
GetWebserviceBatchId
GetImportRecordMarc
AddImportBatch
GetImportBatch
AddAuthToBatch
AddBiblioToBatch
AddItemsToImportBiblio
ModAuthorityInBatch
BatchStageMarcRecords
BatchFindDuplicates
BatchCommitRecords
BatchRevertRecords
CleanBatch
DeleteBatch
GetAllImportBatches
GetStagedWebserviceBatches
GetImportBatchRangeDesc
GetNumberOfNonZ3950ImportBatches
GetImportBiblios
GetImportRecordsRange
GetItemNumbersFromImportBatch
GetImportBatchStatus
SetImportBatchStatus
GetImportBatchOverlayAction
SetImportBatchOverlayAction
GetImportBatchNoMatchAction
SetImportBatchNoMatchAction
GetImportBatchItemAction
SetImportBatchItemAction
GetImportBatchMatcher
SetImportBatchMatcher
GetImportRecordOverlayStatus
SetImportRecordOverlayStatus
GetImportRecordStatus
SetImportRecordStatus
SetMatchedBiblionumber
GetImportRecordMatches
SetImportRecordMatches
RecordsFromMARCXMLFile
RecordsFromISO2709File
RecordsFromMarcPlugin
);
}
=head1 NAME
C4::ImportBatch - manage batches of imported MARC records
=head1 SYNOPSIS
use C4::ImportBatch;
=head1 FUNCTIONS
=head2 GetZ3950BatchId
my $batchid = GetZ3950BatchId($z3950server);
Retrieves the ID of the import batch for the Z39.50
reservoir for the given target. If necessary,
creates the import batch.
=cut
sub GetZ3950BatchId {
my ($z3950server) = @_;
my $dbh = C4::Context->dbh;
my $sth = $dbh->prepare("SELECT import_batch_id FROM import_batches
WHERE batch_type = 'z3950'
AND file_name = ?");
$sth->execute($z3950server);
my $rowref = $sth->fetchrow_arrayref();
$sth->finish();
if (defined $rowref) {
return $rowref->[0];
} else {
my $batch_id = AddImportBatch( {
overlay_action => 'create_new',
import_status => 'staged',
batch_type => 'z3950',
file_name => $z3950server,
} );
return $batch_id;
}
}
=head2 GetWebserviceBatchId
my $batchid = GetWebserviceBatchId();
Retrieves the ID of the import batch for webservice.
If necessary, creates the import batch.
=cut
my $WEBSERVICE_BASE_QRY = <<EOQ;
SELECT import_batch_id FROM import_batches
WHERE batch_type = 'webservice'
AND import_status = 'staged'
EOQ
sub GetWebserviceBatchId {
my ($params) = @_;
my $dbh = C4::Context->dbh;
my $sql = $WEBSERVICE_BASE_QRY;
my @args;
foreach my $field (qw(matcher_id overlay_action nomatch_action item_action)) {
if (my $val = $params->{$field}) {
$sql .= " AND $field = ?";
push @args, $val;
}
}
my $id = $dbh->selectrow_array($sql, undef, @args);
return $id if $id;
$params->{batch_type} = 'webservice';
$params->{import_status} = 'staged';
return AddImportBatch($params);
}
=head2 GetImportRecordMarc
my ($marcblob, $encoding) = GetImportRecordMarc($import_record_id);
=cut
sub GetImportRecordMarc {
my ($import_record_id) = @_;
my $dbh = C4::Context->dbh;
my ( $marc, $encoding ) = $dbh->selectrow_array(q|
SELECT marc, encoding
FROM import_records
WHERE import_record_id = ?
|, undef, $import_record_id );
return $marc, $encoding;
}
=head2 AddImportBatch
my $batch_id = AddImportBatch($params_hash);
=cut
sub AddImportBatch {
my ($params) = @_;
my (@fields, @vals);
foreach (qw( matcher_id template_id branchcode
overlay_action nomatch_action item_action
import_status batch_type file_name comments record_type )) {
if (exists $params->{$_}) {
push @fields, $_;
push @vals, $params->{$_};
}
}
my $dbh = C4::Context->dbh;
$dbh->do("INSERT INTO import_batches (".join( ',', @fields).")
VALUES (".join( ',', map '?', @fields).")",
undef,
@vals);
return $dbh->{'mysql_insertid'};
}
=head2 GetImportBatch
my $row = GetImportBatch($batch_id);
Retrieve a hashref of an import_batches row.
=cut
sub GetImportBatch {
my ($batch_id) = @_;
my $dbh = C4::Context->dbh;
my $sth = $dbh->prepare_cached("SELECT b.*, p.name as profile FROM import_batches b LEFT JOIN import_batch_profiles p ON p.id = b.profile_id WHERE import_batch_id = ?");
$sth->bind_param(1, $batch_id);
$sth->execute();
my $result = $sth->fetchrow_hashref;
$sth->finish();
return $result;
}
=head2 AddBiblioToBatch
my $import_record_id = AddBiblioToBatch($batch_id, $record_sequence,
$marc_record, $encoding, $update_counts);
=cut
sub AddBiblioToBatch {
my $batch_id = shift;
my $record_sequence = shift;
my $marc_record = shift;
my $encoding = shift;
my $update_counts = @_ ? shift : 1;
my $import_record_id = _create_import_record($batch_id, $record_sequence, $marc_record, 'biblio', $encoding, C4::Context->preference('marcflavour'));
_add_biblio_fields($import_record_id, $marc_record);
_update_batch_record_counts($batch_id) if $update_counts;
return $import_record_id;
}
=head2 AddAuthToBatch
my $import_record_id = AddAuthToBatch($batch_id, $record_sequence,
$marc_record, $encoding, $update_counts, [$marc_type]);
=cut
sub AddAuthToBatch {
my $batch_id = shift;
my $record_sequence = shift;
my $marc_record = shift;
my $encoding = shift;
my $update_counts = @_ ? shift : 1;
my $marc_type = shift || C4::Context->preference('marcflavour');
$marc_type = 'UNIMARCAUTH' if $marc_type eq 'UNIMARC';
my $import_record_id = _create_import_record($batch_id, $record_sequence, $marc_record, 'auth', $encoding, $marc_type);
_add_auth_fields($import_record_id, $marc_record);
_update_batch_record_counts($batch_id) if $update_counts;
return $import_record_id;
}
=head2 BatchStageMarcRecords
( $batch_id, $num_records, $num_items, @invalid_records ) =
BatchStageMarcRecords(
$record_type, $encoding,
$marc_records, $file_name,
$marc_modification_template, $comments,
$branch_code, $parse_items,
$leave_as_staging, $progress_interval,
$progress_callback
);
=cut
sub BatchStageMarcRecords {
my $record_type = shift;
my $encoding = shift;
my $marc_records = shift;
my $file_name = shift;
my $marc_modification_template = shift;
my $comments = shift;
my $branch_code = shift;
my $parse_items = shift;
my $leave_as_staging = shift;
# optional callback to monitor status
# of job
my $progress_interval = 0;
my $progress_callback = undef;
if ($#_ == 1) {
$progress_interval = shift;
$progress_callback = shift;
$progress_interval = 0 unless $progress_interval =~ /^\d+$/ and $progress_interval > 0;
$progress_interval = 0 unless 'CODE' eq ref $progress_callback;
}
my $batch_id = AddImportBatch( {
overlay_action => 'create_new',
import_status => 'staging',
batch_type => 'batch',
file_name => $file_name,
comments => $comments,
record_type => $record_type,
} );
if ($parse_items) {
SetImportBatchItemAction($batch_id, 'always_add');
} else {
SetImportBatchItemAction($batch_id, 'ignore');
}
my $marc_type = C4::Context->preference('marcflavour');
$marc_type .= 'AUTH' if ($marc_type eq 'UNIMARC' && $record_type eq 'auth');
my @invalid_records = ();
my $num_valid = 0;
my $num_items = 0;
# FIXME - for now, we're dealing only with bibs
my $rec_num = 0;
foreach my $marc_record (@$marc_records) {
$rec_num++;
if ($progress_interval and (0 == ($rec_num % $progress_interval))) {
&$progress_callback($rec_num);
}
ModifyRecordWithTemplate( $marc_modification_template, $marc_record ) if ( $marc_modification_template );
my $import_record_id;
if (scalar($marc_record->fields()) == 0) {
push @invalid_records, $marc_record;
} else {
# Normalize the record so it doesn't have separated diacritics
SetUTF8Flag($marc_record);
$num_valid++;
if ($record_type eq 'biblio') {
$import_record_id = AddBiblioToBatch($batch_id, $rec_num, $marc_record, $encoding, 0);
if ($parse_items) {
my @import_items_ids = AddItemsToImportBiblio($batch_id, $import_record_id, $marc_record, 0);
$num_items += scalar(@import_items_ids);
}
} elsif ($record_type eq 'auth') {
$import_record_id = AddAuthToBatch($batch_id, $rec_num, $marc_record, $encoding, 0, $marc_type);
}
}
}
unless ($leave_as_staging) {
SetImportBatchStatus($batch_id, 'staged');
}
# FIXME branch_code, number of bibs, number of items
_update_batch_record_counts($batch_id);
if ($progress_interval){
&$progress_callback($rec_num);
}
return ($batch_id, $num_valid, $num_items, @invalid_records);
}
=head2 AddItemsToImportBiblio
my @import_items_ids = AddItemsToImportBiblio($batch_id,
$import_record_id, $marc_record, $update_counts);
=cut
sub AddItemsToImportBiblio {
my $batch_id = shift;
my $import_record_id = shift;
my $marc_record = shift;
my $update_counts = @_ ? shift : 0;
my @import_items_ids = ();
my $dbh = C4::Context->dbh;
my ($item_tag,$item_subfield) = &GetMarcFromKohaField( "items.itemnumber" );
foreach my $item_field ($marc_record->field($item_tag)) {
my $item_marc = MARC::Record->new();
$item_marc->leader("00000 a "); # must set Leader/09 to 'a'
$item_marc->append_fields($item_field);
$marc_record->delete_field($item_field);
my $sth = $dbh->prepare_cached("INSERT INTO import_items (import_record_id, status, marcxml)
VALUES (?, ?, ?)");
$sth->bind_param(1, $import_record_id);
$sth->bind_param(2, 'staged');
$sth->bind_param(3, $item_marc->as_xml("USMARC"));
$sth->execute();
push @import_items_ids, $dbh->{'mysql_insertid'};
$sth->finish();
}
if ($#import_items_ids > -1) {
_update_batch_record_counts($batch_id) if $update_counts;
}
return @import_items_ids;
}
=head2 BatchFindDuplicates
my $num_with_matches = BatchFindDuplicates($batch_id, $matcher,
$max_matches, $progress_interval, $progress_callback);
Goes through the records loaded in the batch and attempts to
find duplicates for each one. Sets the matching status
of each record to "no_match" or "auto_match" as appropriate.
The $max_matches parameter is optional; if it is not supplied,
it defaults to 10.
The $progress_interval and $progress_callback parameters are
optional; if both are supplied, the sub referred to by
$progress_callback will be invoked every $progress_interval
records using the number of records processed as the
singular argument.
=cut
sub BatchFindDuplicates {
my $batch_id = shift;
my $matcher = shift;
my $max_matches = @_ ? shift : 10;
# optional callback to monitor status
# of job
my $progress_interval = 0;
my $progress_callback = undef;
if ($#_ == 1) {
$progress_interval = shift;
$progress_callback = shift;
$progress_interval = 0 unless $progress_interval =~ /^\d+$/ and $progress_interval > 0;
$progress_interval = 0 unless 'CODE' eq ref $progress_callback;
}
my $dbh = C4::Context->dbh;
my $sth = $dbh->prepare("SELECT import_record_id, record_type, marc
FROM import_records
WHERE import_batch_id = ?");
$sth->execute($batch_id);
my $num_with_matches = 0;
my $rec_num = 0;
while (my $rowref = $sth->fetchrow_hashref) {
$rec_num++;
if ($progress_interval and (0 == ($rec_num % $progress_interval))) {
&$progress_callback($rec_num);
}
my $marc_record = MARC::Record->new_from_usmarc($rowref->{'marc'});
my @matches = ();
if (defined $matcher) {
@matches = $matcher->get_matches($marc_record, $max_matches);
}
if (scalar(@matches) > 0) {
$num_with_matches++;
SetImportRecordMatches($rowref->{'import_record_id'}, @matches);
SetImportRecordOverlayStatus($rowref->{'import_record_id'}, 'auto_match');
} else {
SetImportRecordMatches($rowref->{'import_record_id'}, ());
SetImportRecordOverlayStatus($rowref->{'import_record_id'}, 'no_match');
}
}
if ($progress_interval){
&$progress_callback($rec_num);
}
$sth->finish();
return $num_with_matches;
}
=head2 BatchCommitRecords
Takes a hashref containing params for committing the batch - optional parameters 'progress_interval' and
'progress_callback' will define code called every X records.
my ($num_added, $num_updated, $num_items_added, $num_items_replaced, $num_items_errored, $num_ignored) =
BatchCommitRecords({
batch_id => $batch_id,
framework => $framework,
overlay_framework => $overlay_framework,
progress_interval => $progress_interval,
progress_callback => $progress_callback,
});
=cut
sub BatchCommitRecords {
my $params = shift;
my $batch_id = $params->{batch_id};
my $framework = $params->{framework};
my $overlay_framework = $params->{overlay_framework};
my $progress_interval = $params->{progress_interval} // 0;
my $progress_callback = $params->{progress_callback};
$progress_interval = 0 unless $progress_interval && $progress_interval =~ /^\d+$/;
$progress_interval = 0 unless ref($progress_callback) eq 'CODE';
my $schema = Koha::Database->schema;
my $record_type;
my $num_added = 0;
my $num_updated = 0;
my $num_items_added = 0;
my $num_items_replaced = 0;
my $num_items_errored = 0;
my $num_ignored = 0;
# commit (i.e., save, all records in the batch)
my $overlay_action = GetImportBatchOverlayAction($batch_id);
my $nomatch_action = GetImportBatchNoMatchAction($batch_id);
my $item_action = GetImportBatchItemAction($batch_id);
my $item_tag;
my $item_subfield;
my $dbh = C4::Context->dbh;
my $sth = $dbh->prepare("SELECT import_records.import_record_id, record_type, status, overlay_status, marc, encoding
FROM import_records
LEFT JOIN import_auths ON (import_records.import_record_id=import_auths.import_record_id)
LEFT JOIN import_biblios ON (import_records.import_record_id=import_biblios.import_record_id)
WHERE import_batch_id = ?");
$sth->execute($batch_id);
my $marcflavour = C4::Context->preference('marcflavour');
my $userenv = C4::Context->userenv;
my $logged_in_patron = Koha::Patrons->find( $userenv->{number} );
my $rec_num = 0;
my @biblio_ids;
my @updated_ids;
while (my $rowref = $sth->fetchrow_hashref) {
$schema->txn_begin;
$record_type = $rowref->{'record_type'};
$rec_num++;
if ($progress_interval and (0 == ($rec_num % $progress_interval))) {
# report progress
&$progress_callback( $rec_num );
}
if ($rowref->{'status'} eq 'error' or $rowref->{'status'} eq 'imported') {
$num_ignored++;
next;
}
my $marc_type;
if ($marcflavour eq 'UNIMARC' && $record_type eq 'auth') {
$marc_type = 'UNIMARCAUTH';
} elsif ($marcflavour eq 'UNIMARC') {
$marc_type = 'UNIMARC';
} else {
$marc_type = 'USMARC';
}
my $marc_record = MARC::Record->new_from_usmarc($rowref->{'marc'});
if ($record_type eq 'biblio') {
# remove any item tags - rely on _batchCommitItems
($item_tag,$item_subfield) = &GetMarcFromKohaField( "items.itemnumber" );
foreach my $item_field ($marc_record->field($item_tag)) {
$marc_record->delete_field($item_field);
}
if(C4::Context->preference('autoControlNumber') eq 'biblionumber'){
my @control_num = $marc_record->field('001');
$marc_record->delete_fields(@control_num);
}
}
my ($record_result, $item_result, $record_match) =
_get_commit_action($overlay_action, $nomatch_action, $item_action,
$rowref->{'overlay_status'}, $rowref->{'import_record_id'}, $record_type);
my $recordid;
my $query;
if ($record_result eq 'create_new') {
$num_added++;
if ($record_type eq 'biblio') {
my $biblioitemnumber;
($recordid, $biblioitemnumber) = AddBiblio($marc_record, $framework, { skip_record_index => 1 });
push @biblio_ids, $recordid if $recordid;
$query = "UPDATE import_biblios SET matched_biblionumber = ? WHERE import_record_id = ?"; # FIXME call SetMatchedBiblionumber instead
if ($item_result eq 'create_new' || $item_result eq 'replace') {
my ($bib_items_added, $bib_items_replaced, $bib_items_errored) = _batchCommitItems($rowref->{'import_record_id'}, $recordid, $item_result, $biblioitemnumber);
$num_items_added += $bib_items_added;
$num_items_replaced += $bib_items_replaced;
$num_items_errored += $bib_items_errored;
}
} else {
$recordid = AddAuthority($marc_record, undef, GuessAuthTypeCode($marc_record));
$query = "UPDATE import_auths SET matched_authid = ? WHERE import_record_id = ?";
}
my $sth = $dbh->prepare_cached($query);
$sth->execute($recordid, $rowref->{'import_record_id'});
$sth->finish();
SetImportRecordStatus($rowref->{'import_record_id'}, 'imported');
} elsif ($record_result eq 'replace') {
$num_updated++;
$recordid = $record_match;
my $oldxml;
if ($record_type eq 'biblio') {
my $oldbiblio = Koha::Biblios->find( $recordid );
$oldxml = GetXmlBiblio($recordid);
# remove item fields so that they don't get
# added again if record is reverted
# FIXME: GetXmlBiblio output should not contain item info any more! So the next foreach should not be needed. Does not hurt either; may remove old 952s that should not have been there anymore.
my $old_marc = MARC::Record->new_from_xml(StripNonXmlChars($oldxml), 'UTF-8', $rowref->{'encoding'}, $marc_type);
foreach my $item_field ($old_marc->field($item_tag)) {
$old_marc->delete_field($item_field);
}
$oldxml = $old_marc->as_xml($marc_type);
my $context = { source => 'batchimport' };
if ($logged_in_patron) {
$context->{categorycode} = $logged_in_patron->categorycode;
$context->{userid} = $logged_in_patron->userid;
}
ModBiblio(
$marc_record,
$recordid,
$overlay_framework // $oldbiblio->frameworkcode,
{
overlay_context => $context,
skip_record_index => 1,
skip_holds_queue => 1,
}
);
push @biblio_ids, $recordid;
push @updated_ids, $recordid;
$query = "UPDATE import_biblios SET matched_biblionumber = ? WHERE import_record_id = ?"; # FIXME call SetMatchedBiblionumber instead
if ($item_result eq 'create_new' || $item_result eq 'replace') {
my ($bib_items_added, $bib_items_replaced, $bib_items_errored) = _batchCommitItems($rowref->{'import_record_id'}, $recordid, $item_result);
$num_items_added += $bib_items_added;
$num_items_replaced += $bib_items_replaced;
$num_items_errored += $bib_items_errored;
}
} else {
$oldxml = GetAuthorityXML($recordid);
ModAuthority($recordid, $marc_record, GuessAuthTypeCode($marc_record));
$query = "UPDATE import_auths SET matched_authid = ? WHERE import_record_id = ?";
}
# Combine xml update, SetImportRecordOverlayStatus, and SetImportRecordStatus updates into a single update for efficiency, especially in a transaction
my $sth = $dbh->prepare_cached("UPDATE import_records SET marcxml_old = ?, status = ?, overlay_status = ? WHERE import_record_id = ?");
$sth->execute( $oldxml, 'imported', 'match_applied', $rowref->{'import_record_id'} );
$sth->finish();
my $sth2 = $dbh->prepare_cached($query);
$sth2->execute($recordid, $rowref->{'import_record_id'});
$sth2->finish();
} elsif ($record_result eq 'ignore') {
$recordid = $record_match;
$num_ignored++;
if ($record_type eq 'biblio' and defined $recordid and ( $item_result eq 'create_new' || $item_result eq 'replace' ) ) {
my ($bib_items_added, $bib_items_replaced, $bib_items_errored) = _batchCommitItems($rowref->{'import_record_id'}, $recordid, $item_result);
push @biblio_ids, $recordid if $bib_items_added || $bib_items_replaced;
$num_items_added += $bib_items_added;
$num_items_replaced += $bib_items_replaced;
$num_items_errored += $bib_items_errored;
# still need to record the matched biblionumber so that the
# items can be reverted
my $sth2 = $dbh->prepare_cached("UPDATE import_biblios SET matched_biblionumber = ? WHERE import_record_id = ?"); # FIXME call SetMatchedBiblionumber instead
$sth2->execute($recordid, $rowref->{'import_record_id'});
SetImportRecordOverlayStatus($rowref->{'import_record_id'}, 'match_applied');
}
SetImportRecordStatus($rowref->{'import_record_id'}, 'ignored');
}
$schema->txn_commit;
}
if ($progress_interval){
&$progress_callback($rec_num);
}
$sth->finish();
SetImportBatchStatus($batch_id, 'imported');
if (@biblio_ids) {
my $indexer = Koha::SearchEngine::Indexer->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } );
$indexer->index_records( \@biblio_ids, "specialUpdate", "biblioserver" );
}
Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue( { biblio_ids => \@updated_ids } )
if ( @updated_ids && C4::Context->preference('RealTimeHoldsQueue') );
return ($num_added, $num_updated, $num_items_added, $num_items_replaced, $num_items_errored, $num_ignored);
}
=head2 _batchCommitItems
($num_items_added, $num_items_errored) =
_batchCommitItems($import_record_id, $biblionumber, [$action, $biblioitemnumber]);
Private function for batch committing item changes. We do not trigger a re-index here, that is left to the caller.
=cut
sub _batchCommitItems {
my ( $import_record_id, $biblionumber, $action, $biblioitemnumber ) = @_;
my $dbh = C4::Context->dbh;
my $num_items_added = 0;
my $num_items_errored = 0;
my $num_items_replaced = 0;
my $sth = $dbh->prepare( "
SELECT import_items_id, import_items.marcxml, encoding
FROM import_items
JOIN import_records USING (import_record_id)
WHERE import_record_id = ?
ORDER BY import_items_id
" );
$sth->bind_param( 1, $import_record_id );
$sth->execute();
while ( my $row = $sth->fetchrow_hashref() ) {
my $item_marc = MARC::Record->new_from_xml( StripNonXmlChars( $row->{'marcxml'} ), 'UTF-8', $row->{'encoding'} );
# Delete date_due subfield as to not accidentally delete item checkout due dates
my ( $MARCfield, $MARCsubfield ) = GetMarcFromKohaField( 'items.onloan' );
$item_marc->field($MARCfield)->delete_subfield( code => $MARCsubfield );
my $item = TransformMarcToKoha({ record => $item_marc, kohafields => ['items.barcode','items.itemnumber'] });
my $item_match;
my $duplicate_barcode = exists( $item->{'barcode'} );
my $duplicate_itemnumber = exists( $item->{'itemnumber'} );
# We assume that when replacing items we do not want to move them - the onus is on the importer to
# ensure the correct items/records are being updated
my $updsth = $dbh->prepare("UPDATE import_items SET status = ?, itemnumber = ?, import_error = ? WHERE import_items_id = ?");
if (
$action eq "replace" &&
$duplicate_itemnumber &&
( $item_match = Koha::Items->find( $item->{itemnumber} ))
) {
# Duplicate itemnumbers have precedence, that way we can update barcodes by overlaying
ModItemFromMarc( $item_marc, $item_match->biblionumber, $item->{itemnumber}, { skip_record_index => 1 } );
$updsth->bind_param( 1, 'imported' );
$updsth->bind_param( 2, $item->{itemnumber} );
$updsth->bind_param( 3, undef );
$updsth->bind_param( 4, $row->{'import_items_id'} );
$updsth->execute();
$updsth->finish();
$num_items_replaced++;
} elsif (
$action eq "replace" &&
$duplicate_barcode &&
( $item_match = Koha::Items->find({ barcode => $item->{'barcode'} }) )
) {
ModItemFromMarc( $item_marc, $item_match->biblionumber, $item_match->itemnumber, { skip_record_index => 1 } );
$updsth->bind_param( 1, 'imported' );
$updsth->bind_param( 2, $item->{itemnumber} );
$updsth->bind_param( 3, undef );
$updsth->bind_param( 4, $row->{'import_items_id'} );
$updsth->execute();
$updsth->finish();
$num_items_replaced++;
} elsif (
# We aren't replacing, but the incoming file has a barcode, we need to check if it exists
$duplicate_barcode &&
( $item_match = Koha::Items->find({ barcode => $item->{'barcode'} }) )
) {
$updsth->bind_param( 1, 'error' );
$updsth->bind_param( 2, undef );
$updsth->bind_param( 3, 'duplicate item barcode' );
$updsth->bind_param( 4, $row->{'import_items_id'} );
$updsth->execute();
$num_items_errored++;
} else {
# Remove the itemnumber if it exists, we want to create a new item
my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber" );
$item_marc->field($itemtag)->delete_subfield( code => $itemsubfield );
my ( $item_biblionumber, $biblioitemnumber, $itemnumber ) = AddItemFromMarc( $item_marc, $biblionumber, { biblioitemnumber => $biblioitemnumber, skip_record_index => 1 } );
if( $itemnumber ) {
$updsth->bind_param( 1, 'imported' );
$updsth->bind_param( 2, $itemnumber );
$updsth->bind_param( 3, undef );
$updsth->bind_param( 4, $row->{'import_items_id'} );
$updsth->execute();
$updsth->finish();
$num_items_added++;
}
}
}
return ( $num_items_added, $num_items_replaced, $num_items_errored );
}
=head2 BatchRevertRecords
my ($num_deleted, $num_errors, $num_reverted, $num_items_deleted,
$num_ignored) = BatchRevertRecords($batch_id);
=cut
sub BatchRevertRecords {
my $batch_id = shift;
my $logger = Koha::Logger->get( { category => 'C4.ImportBatch' } );
$logger->trace("C4::ImportBatch::BatchRevertRecords( $batch_id )");
my $record_type;
my $num_deleted = 0;
my $num_errors = 0;
my $num_reverted = 0;
my $num_ignored = 0;
my $num_items_deleted = 0;
# commit (i.e., save, all records in the batch)
SetImportBatchStatus($batch_id, 'reverting');
my $overlay_action = GetImportBatchOverlayAction($batch_id);
my $nomatch_action = GetImportBatchNoMatchAction($batch_id);
my $dbh = C4::Context->dbh;
my $sth = $dbh->prepare("SELECT import_records.import_record_id, record_type, status, overlay_status, marcxml_old, encoding, matched_biblionumber, matched_authid
FROM import_records
LEFT JOIN import_auths ON (import_records.import_record_id=import_auths.import_record_id)
LEFT JOIN import_biblios ON (import_records.import_record_id=import_biblios.import_record_id)
WHERE import_batch_id = ?");
$sth->execute($batch_id);
my $marc_type;
my $marcflavour = C4::Context->preference('marcflavour');
while (my $rowref = $sth->fetchrow_hashref) {
$record_type = $rowref->{'record_type'};
if ($rowref->{'status'} eq 'error' or $rowref->{'status'} eq 'reverted') {
$num_ignored++;
next;
}
if ($marcflavour eq 'UNIMARC' && $record_type eq 'auth') {
$marc_type = 'UNIMARCAUTH';
} elsif ($marcflavour eq 'UNIMARC') {
$marc_type = 'UNIMARC';
} else {
$marc_type = 'USMARC';
}
my $record_result = _get_revert_action($overlay_action, $rowref->{'overlay_status'}, $rowref->{'status'});
if ($record_result eq 'delete') {
my $error = undef;
if ($record_type eq 'biblio') {
$num_items_deleted += BatchRevertItems($rowref->{'import_record_id'}, $rowref->{'matched_biblionumber'});
$error = DelBiblio($rowref->{'matched_biblionumber'});
} else {
DelAuthority({ authid => $rowref->{'matched_authid'} });
}
if (defined $error) {
$num_errors++;
} else {
$num_deleted++;
SetImportRecordStatus($rowref->{'import_record_id'}, 'reverted');
}
} elsif ($record_result eq 'restore') {
$num_reverted++;
my $old_record = MARC::Record->new_from_xml(StripNonXmlChars($rowref->{'marcxml_old'}), 'UTF-8', $rowref->{'encoding'}, $marc_type);
if ($record_type eq 'biblio') {
my $biblionumber = $rowref->{'matched_biblionumber'};
my $oldbiblio = Koha::Biblios->find( $biblionumber );
$logger->info("C4::ImportBatch::BatchRevertRecords: Biblio record $biblionumber does not exist, restoration of this record was skipped") unless $oldbiblio;
next unless $oldbiblio; # Record has since been deleted. Deleted records should stay deleted.
$num_items_deleted += BatchRevertItems($rowref->{'import_record_id'}, $rowref->{'matched_biblionumber'});
ModBiblio($old_record, $biblionumber, $oldbiblio->frameworkcode);
} else {
my $authid = $rowref->{'matched_authid'};
ModAuthority($authid, $old_record, GuessAuthTypeCode($old_record));
}
SetImportRecordStatus($rowref->{'import_record_id'}, 'reverted');
} elsif ($record_result eq 'ignore') {
if ($record_type eq 'biblio') {
$num_items_deleted += BatchRevertItems($rowref->{'import_record_id'}, $rowref->{'matched_biblionumber'});
}
SetImportRecordStatus($rowref->{'import_record_id'}, 'reverted');
}
my $query;
if ($record_type eq 'biblio') {
# remove matched_biblionumber only if there is no 'imported' item left
$query = "UPDATE import_biblios SET matched_biblionumber = NULL WHERE import_record_id = ?"; # FIXME Remove me
$query = "UPDATE import_biblios SET matched_biblionumber = NULL WHERE import_record_id = ? AND NOT EXISTS (SELECT * FROM import_items WHERE import_items.import_record_id=import_biblios.import_record_id and status='imported')";
} else {
$query = "UPDATE import_auths SET matched_authid = NULL WHERE import_record_id = ?";
}
my $sth2 = $dbh->prepare_cached($query);
$sth2->execute($rowref->{'import_record_id'});
}
$sth->finish();
SetImportBatchStatus($batch_id, 'reverted');
return ($num_deleted, $num_errors, $num_reverted, $num_items_deleted, $num_ignored);
}
=head2 BatchRevertItems
my $num_items_deleted = BatchRevertItems($import_record_id, $biblionumber);
=cut
sub BatchRevertItems {
my ($import_record_id, $biblionumber) = @_;
my $dbh = C4::Context->dbh;
my $num_items_deleted = 0;
my $sth = $dbh->prepare_cached("SELECT import_items_id, itemnumber
FROM import_items
JOIN items USING (itemnumber)
WHERE import_record_id = ?");
$sth->bind_param(1, $import_record_id);
$sth->execute();
while (my $row = $sth->fetchrow_hashref()) {
my $item = Koha::Items->find($row->{itemnumber});
if ($item->safe_delete){
my $updsth = $dbh->prepare("UPDATE import_items SET status = ? WHERE import_items_id = ?");
$updsth->bind_param(1, 'reverted');
$updsth->bind_param(2, $row->{'import_items_id'});
$updsth->execute();
$updsth->finish();
$num_items_deleted++;
}
else {
next;
}
}
$sth->finish();
return $num_items_deleted;
}
=head2 CleanBatch
CleanBatch($batch_id)
Deletes all staged records from the import batch
and sets the status of the batch to 'cleaned'. Note
that deleting a stage record does *not* affect
any record that has been committed to the database.
=cut
sub CleanBatch {
my $batch_id = shift;
return unless defined $batch_id;
C4::Context->dbh->do('DELETE FROM import_records WHERE import_batch_id = ?', {}, $batch_id);
SetImportBatchStatus($batch_id, 'cleaned');
}
=head2 DeleteBatch
DeleteBatch($batch_id)
Deletes the record from the database. This can only be done
once the batch has been cleaned.
=cut
sub DeleteBatch {
my $batch_id = shift;
return unless defined $batch_id;
my $dbh = C4::Context->dbh;
my $sth = $dbh->prepare('DELETE FROM import_batches WHERE import_batch_id = ?');
$sth->execute( $batch_id );
}
=head2 GetAllImportBatches
my $results = GetAllImportBatches();
Returns a references to an array of hash references corresponding
to all import_batches rows (of batch_type 'batch'), sorted in
ascending order by import_batch_id.
=cut
sub GetAllImportBatches {
my $dbh = C4::Context->dbh;
my $sth = $dbh->prepare_cached("SELECT * FROM import_batches
WHERE batch_type IN ('batch', 'webservice')
ORDER BY import_batch_id ASC");