ImportBatch.pm 57 KB
Newer Older
1 2
package C4::ImportBatch;

3
# Copyright (C) 2007 LibLime, 2012 C & P Bibliography Services
4 5 6
#
# This file is part of Koha.
#
7 8 9 10
# 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.
11
#
12 13 14 15
# 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.
16
#
17 18
# You should have received a copy of the GNU General Public License
# along with Koha; if not, see <http://www.gnu.org/licenses>.
19 20

use strict;
21 22
use warnings;

23 24 25
use C4::Context;
use C4::Koha;
use C4::Biblio;
26
use C4::Items;
27
use C4::Charset;
28
use C4::AuthoritiesMarc;
29
use C4::MarcModificationTemplates;
30
use Koha::Plugins::Handler;
31
use Koha::Logger;
32

33
use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
34

35 36 37 38
BEGIN {
	require Exporter;
	@ISA    = qw(Exporter);
	@EXPORT = qw(
39
    GetZ3950BatchId
40
    GetWebserviceBatchId
41
    GetImportRecordMarc
42
    GetImportRecordMarcXML
43
    AddImportBatch
44
    GetImportBatch
45
    AddAuthToBatch
46
    AddBiblioToBatch
47
    AddItemsToImportBiblio
48
    ModAuthorityInBatch
49
    ModBiblioInBatch
50 51

    BatchStageMarcRecords
52 53 54
    BatchFindDuplicates
    BatchCommitRecords
    BatchRevertRecords
55
    CleanBatch
56
    DeleteBatch
57

58
    GetAllImportBatches
59
    GetStagedWebserviceBatches
60 61
    GetImportBatchRangeDesc
    GetNumberOfNonZ3950ImportBatches
62
    GetImportBiblios
63
    GetImportRecordsRange
64
	GetItemNumbersFromImportBatch
65 66 67 68 69
    
    GetImportBatchStatus
    SetImportBatchStatus
    GetImportBatchOverlayAction
    SetImportBatchOverlayAction
70 71 72 73
    GetImportBatchNoMatchAction
    SetImportBatchNoMatchAction
    GetImportBatchItemAction
    SetImportBatchItemAction
74 75
    GetImportBatchMatcher
    SetImportBatchMatcher
76 77
    GetImportRecordOverlayStatus
    SetImportRecordOverlayStatus
78 79 80
    GetImportRecordStatus
    SetImportRecordStatus
    GetImportRecordMatches
81
    SetImportRecordMatches
82 83 84
	);
}

85 86
our $logger = Koha::Logger->get( { category => 'C4.ImportBatch' } );

87 88 89 90 91 92 93 94 95
=head1 NAME

C4::ImportBatch - manage batches of imported MARC records

=head1 SYNOPSIS

use C4::ImportBatch;

=head1 FUNCTIONS
96 97 98

=head2 GetZ3950BatchId

Andrew Elwell's avatar
Andrew Elwell committed
99
  my $batchid = GetZ3950BatchId($z3950server);
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119

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 {
120 121 122 123 124 125
        my $batch_id = AddImportBatch( {
                overlay_action => 'create_new',
                import_status => 'staged',
                batch_type => 'z3950',
                file_name => $z3950server,
            } );
126 127 128 129 130
        return $batch_id;
    }
    
}

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
=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);
}

165 166
=head2 GetImportRecordMarc

Andrew Elwell's avatar
Andrew Elwell committed
167
  my ($marcblob, $encoding) = GetImportRecordMarc($import_record_id);
168 169 170 171 172 173 174

=cut

sub GetImportRecordMarc {
    my ($import_record_id) = @_;

    my $dbh = C4::Context->dbh;
175 176 177 178 179 180
    my ( $marc, $encoding ) = $dbh->selectrow_array(q|
        SELECT marc, encoding
        FROM import_records
        WHERE import_record_id = ?
    |, undef, $import_record_id );

Paul Poulain's avatar
Paul Poulain committed
181
    return $marc, $encoding;
182 183 184 185 186 187 188
}

sub GetRecordFromImportBiblio {
    my ( $import_record_id, $embed_items ) = @_;

    my ($marc) = GetImportRecordMarc($import_record_id);
    my $record = MARC::Record->new_from_usmarc($marc);
189

190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
    EmbedItemsInImportBiblio( $record, $import_record_id ) if $embed_items;

    return $record;
}

sub EmbedItemsInImportBiblio {
    my ( $record, $import_record_id ) = @_;
    my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber", '');
    my $dbh = C4::Context->dbh;
    my $import_items = $dbh->selectall_arrayref(q|
        SELECT import_items.marcxml
        FROM import_items
        WHERE import_record_id = ?
    |, { Slice => {} }, $import_record_id );
    my @item_fields;
    for my $import_item ( @$import_items ) {
        my $item_marc = MARC::Record::new_from_xml($import_item->{marcxml});
        push @item_fields, $item_marc->field($itemtag);
    }
    $record->append_fields(@item_fields);
    return $record;
211 212
}

213
=head2 GetImportRecordMarcXML
214

215
  my $marcxml = GetImportRecordMarcXML($import_record_id);
216 217 218

=cut

219 220
sub GetImportRecordMarcXML {
    my ($import_record_id) = @_;
221 222

    my $dbh = C4::Context->dbh;
223 224 225
    my $sth = $dbh->prepare("SELECT marcxml FROM import_records WHERE import_record_id = ?");
    $sth->execute($import_record_id);
    my ($marcxml) = $sth->fetchrow();
226
    $sth->finish();
227
    return $marcxml;
228

229 230 231
}

=head2 AddImportBatch
232

233 234 235 236 237 238 239 240 241 242
  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
243
                 import_status batch_type file_name comments record_type )) {
244 245 246 247 248 249 250 251 252 253 254
        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'};
255 256
}

257 258
=head2 GetImportBatch 

Andrew Elwell's avatar
Andrew Elwell committed
259
  my $row = GetImportBatch($batch_id);
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277

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 * FROM import_batches WHERE import_batch_id = ?");
    $sth->bind_param(1, $batch_id);
    $sth->execute();
    my $result = $sth->fetchrow_hashref;
    $sth->finish();
    return $result;

}

278 279
=head2 AddBiblioToBatch 

Andrew Elwell's avatar
Andrew Elwell committed
280 281
  my $import_record_id = AddBiblioToBatch($batch_id, $record_sequence, 
                $marc_record, $encoding, $z3950random, $update_counts);
282

283 284 285
=cut

sub AddBiblioToBatch {
286 287 288 289 290 291
    my $batch_id = shift;
    my $record_sequence = shift;
    my $marc_record = shift;
    my $encoding = shift;
    my $z3950random = shift;
    my $update_counts = @_ ? shift : 1;
292

293
    my $import_record_id = _create_import_record($batch_id, $record_sequence, $marc_record, 'biblio', $encoding, $z3950random, C4::Context->preference('marcflavour'));
294
    _add_biblio_fields($import_record_id, $marc_record);
295
    _update_batch_record_counts($batch_id) if $update_counts;
296 297 298 299 300
    return $import_record_id;
}

=head2 ModBiblioInBatch

Andrew Elwell's avatar
Andrew Elwell committed
301
  ModBiblioInBatch($import_record_id, $marc_record);
302

303 304 305 306 307
=cut

sub ModBiblioInBatch {
    my ($import_record_id, $marc_record) = @_;

308
    _update_import_record_marc($import_record_id, $marc_record, C4::Context->preference('marcflavour'));
309 310 311 312
    _update_biblio_fields($import_record_id, $marc_record);

}

313 314 315
=head2 AddAuthToBatch

  my $import_record_id = AddAuthToBatch($batch_id, $record_sequence,
316
                $marc_record, $encoding, $z3950random, $update_counts, [$marc_type]);
317 318 319 320 321 322 323 324 325 326

=cut

sub AddAuthToBatch {
    my $batch_id = shift;
    my $record_sequence = shift;
    my $marc_record = shift;
    my $encoding = shift;
    my $z3950random = shift;
    my $update_counts = @_ ? shift : 1;
327 328 329
    my $marc_type = shift || C4::Context->preference('marcflavour');

    $marc_type = 'UNIMARCAUTH' if $marc_type eq 'UNIMARC';
330

331
    my $import_record_id = _create_import_record($batch_id, $record_sequence, $marc_record, 'auth', $encoding, $z3950random, $marc_type);
332 333 334 335 336 337 338 339 340 341 342 343 344 345
    _add_auth_fields($import_record_id, $marc_record);
    _update_batch_record_counts($batch_id) if $update_counts;
    return $import_record_id;
}

=head2 ModAuthInBatch

  ModAuthInBatch($import_record_id, $marc_record);

=cut

sub ModAuthInBatch {
    my ($import_record_id, $marc_record) = @_;

346 347
    my $marcflavour = C4::Context->preference('marcflavour');
    _update_import_record_marc($import_record_id, $marc_record, $marcflavour eq 'UNIMARC' ? 'UNIMARCAUTH' : 'USMARC');
348 349 350

}

351 352
=head2 BatchStageMarcRecords

353 354
( $batch_id, $num_records, $num_items, @invalid_records ) =
  BatchStageMarcRecords(
355 356
    $record_type,                $encoding,
    $marc_records,               $file_name,
357 358 359 360 361
    $marc_modification_template, $comments,
    $branch_code,                $parse_items,
    $leave_as_staging,           $progress_interval,
    $progress_callback
  );
362 363 364

=cut

365
sub BatchStageMarcRecords {
366
    my $record_type = shift;
367
    my $encoding = shift;
368 369
    my $marc_records = shift;
    my $file_name = shift;
370
    my $marc_modification_template = shift;
371 372 373 374
    my $comments = shift;
    my $branch_code = shift;
    my $parse_items = shift;
    my $leave_as_staging = shift;
375

376 377 378 379 380 381 382 383 384 385 386
    # 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;
    } 
    
387 388 389 390 391 392
    my $batch_id = AddImportBatch( {
            overlay_action => 'create_new',
            import_status => 'staging',
            batch_type => 'batch',
            file_name => $file_name,
            comments => $comments,
393
            record_type => $record_type,
394
        } );
395 396 397 398 399 400
    if ($parse_items) {
        SetImportBatchItemAction($batch_id, 'always_add');
    } else {
        SetImportBatchItemAction($batch_id, 'ignore');
    }

401

402 403
    my $marc_type = C4::Context->preference('marcflavour');
    $marc_type .= 'AUTH' if ($marc_type eq 'UNIMARC' && $record_type eq 'auth');
404 405
    my @invalid_records = ();
    my $num_valid = 0;
406
    my $num_items = 0;
407 408
    # FIXME - for now, we're dealing only with bibs
    my $rec_num = 0;
409
    foreach my $marc_record (@$marc_records) {
410
        $rec_num++;
411 412 413
        if ($progress_interval and (0 == ($rec_num % $progress_interval))) {
            &$progress_callback($rec_num);
        }
414

415 416
        ModifyRecordWithTemplate( $marc_modification_template, $marc_record ) if ( $marc_modification_template );

417 418
        my $import_record_id;
        if (scalar($marc_record->fields()) == 0) {
419
            push @invalid_records, $marc_record;
420
        } else {
421 422 423 424

            # Normalize the record so it doesn't have separated diacritics
            SetUTF8Flag($marc_record);

425
            $num_valid++;
426 427 428 429 430 431 432
            if ($record_type eq 'biblio') {
                $import_record_id = AddBiblioToBatch($batch_id, $rec_num, $marc_record, $encoding, int(rand(99999)), 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') {
433
                $import_record_id = AddAuthToBatch($batch_id, $rec_num, $marc_record, $encoding, int(rand(99999)), 0, $marc_type);
434
            }
435 436 437 438 439
        }
    }
    unless ($leave_as_staging) {
        SetImportBatchStatus($batch_id, 'staged');
    }
440 441
    # FIXME branch_code, number of bibs, number of items
    _update_batch_record_counts($batch_id);
442 443 444 445 446
    return ($batch_id, $num_valid, $num_items, @invalid_records);
}

=head2 AddItemsToImportBiblio

Andrew Elwell's avatar
Andrew Elwell committed
447 448
  my @import_items_ids = AddItemsToImportBiblio($batch_id, 
                $import_record_id, $marc_record, $update_counts);
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463

=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();
464
        $item_marc->leader("00000    a              "); # must set Leader/09 to 'a'
465 466 467 468 469 470 471 472 473 474 475 476 477 478
        $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());
        $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;
479
        _update_import_record_marc($import_record_id, $marc_record, C4::Context->preference('marcflavour'));
480 481
    }
    return @import_items_ids;
482 483
}

484
=head2 BatchFindDuplicates
485

486
  my $num_with_matches = BatchFindDuplicates($batch_id, $matcher,
Andrew Elwell's avatar
Andrew Elwell committed
487
             $max_matches, $progress_interval, $progress_callback);
488 489

Goes through the records loaded in the batch and attempts to 
490
find duplicates for each one.  Sets the matching status 
Galen Charlton's avatar
Galen Charlton committed
491
of each record to "no_match" or "auto_match" as appropriate.
492 493 494 495

The $max_matches parameter is optional; if it is not supplied,
it defaults to 10.

496 497 498 499 500 501
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.

502 503
=cut

504
sub BatchFindDuplicates {
505 506 507 508
    my $batch_id = shift;
    my $matcher = shift;
    my $max_matches = @_ ? shift : 10;

509 510 511 512 513 514 515 516 517 518 519
    # 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;
    }

520 521
    my $dbh = C4::Context->dbh;

522
    my $sth = $dbh->prepare("SELECT import_record_id, record_type, marc
523 524 525 526
                             FROM import_records
                             WHERE import_batch_id = ?");
    $sth->execute($batch_id);
    my $num_with_matches = 0;
527
    my $rec_num = 0;
528
    while (my $rowref = $sth->fetchrow_hashref) {
529 530 531 532
        $rec_num++;
        if ($progress_interval and (0 == ($rec_num % $progress_interval))) {
            &$progress_callback($rec_num);
        }
533
        my $marc_record = MARC::Record->new_from_usmarc($rowref->{'marc'});
534 535 536 537
        my @matches = ();
        if (defined $matcher) {
            @matches = $matcher->get_matches($marc_record, $max_matches);
        }
538 539 540 541 542
        if (scalar(@matches) > 0) {
            $num_with_matches++;
            SetImportRecordMatches($rowref->{'import_record_id'}, @matches);
            SetImportRecordOverlayStatus($rowref->{'import_record_id'}, 'auto_match');
        } else {
543
            SetImportRecordMatches($rowref->{'import_record_id'}, ());
544 545 546 547 548 549 550
            SetImportRecordOverlayStatus($rowref->{'import_record_id'}, 'no_match');
        }
    }
    $sth->finish();
    return $num_with_matches;
}

551
=head2 BatchCommitRecords
552

553
  my ($num_added, $num_updated, $num_items_added, $num_items_replaced, $num_items_errored, $num_ignored) =
554 555
        BatchCommitRecords($batch_id, $framework,
        $progress_interval, $progress_callback);
556 557 558

=cut

559
sub BatchCommitRecords {
560
    my $batch_id = shift;
561
    my $framework = shift;
562

563 564 565 566 567 568 569 570 571 572 573
    # 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;
    }

574
    my $record_type;
575 576
    my $num_added = 0;
    my $num_updated = 0;
577
    my $num_items_added = 0;
578
    my $num_items_replaced = 0;
579
    my $num_items_errored = 0;
580 581 582 583
    my $num_ignored = 0;
    # commit (i.e., save, all records in the batch)
    SetImportBatchStatus('importing');
    my $overlay_action = GetImportBatchOverlayAction($batch_id);
584 585
    my $nomatch_action = GetImportBatchNoMatchAction($batch_id);
    my $item_action = GetImportBatchItemAction($batch_id);
586 587
    my $item_tag;
    my $item_subfield;
588
    my $dbh = C4::Context->dbh;
589
    my $sth = $dbh->prepare("SELECT import_records.import_record_id, record_type, status, overlay_status, marc, encoding
590
                             FROM import_records
591 592
                             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)
593 594
                             WHERE import_batch_id = ?");
    $sth->execute($batch_id);
595
    my $marcflavour = C4::Context->preference('marcflavour');
596
    my $rec_num = 0;
597
    while (my $rowref = $sth->fetchrow_hashref) {
598
        $record_type = $rowref->{'record_type'};
599 600 601 602
        $rec_num++;
        if ($progress_interval and (0 == ($rec_num % $progress_interval))) {
            &$progress_callback($rec_num);
        }
603 604
        if ($rowref->{'status'} eq 'error' or $rowref->{'status'} eq 'imported') {
            $num_ignored++;
605
            next;
606
        }
607

608 609 610 611 612 613 614 615
        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';
        }
616
        my $marc_record = MARC::Record->new_from_usmarc($rowref->{'marc'});
617

618 619 620 621 622 623
        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);
            }
624 625
        }

626
        my ($record_result, $item_result, $record_match) =
627
            _get_commit_action($overlay_action, $nomatch_action, $item_action, 
628
                               $rowref->{'overlay_status'}, $rowref->{'import_record_id'}, $record_type);
629

630 631 632
        my $recordid;
        my $query;
        if ($record_result eq 'create_new') {
633
            $num_added++;
634 635 636 637
            if ($record_type eq 'biblio') {
                my $biblioitemnumber;
                ($recordid, $biblioitemnumber) = AddBiblio($marc_record, $framework);
                $query = "UPDATE import_biblios SET matched_biblionumber = ? WHERE import_record_id = ?";
638 639
                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);
640
                    $num_items_added += $bib_items_added;
641
                    $num_items_replaced += $bib_items_replaced;
642 643 644
                    $num_items_errored += $bib_items_errored;
                }
            } else {
645
                $recordid = AddAuthority($marc_record, undef, GuessAuthTypeCode($marc_record));
646
                $query = "UPDATE import_auths SET matched_authid = ? WHERE import_record_id = ?";
647
            }
648 649 650
            my $sth = $dbh->prepare_cached($query);
            $sth->execute($recordid, $rowref->{'import_record_id'});
            $sth->finish();
651
            SetImportRecordStatus($rowref->{'import_record_id'}, 'imported');
652
        } elsif ($record_result eq 'replace') {
653
            $num_updated++;
654 655 656
            $recordid = $record_match;
            my $oldxml;
            if ($record_type eq 'biblio') {
657
                my $oldbiblio = Koha::Biblios->find( $recordid );
658 659 660 661
                $oldxml = GetXmlBiblio($recordid);

                # remove item fields so that they don't get
                # added again if record is reverted
662
                # 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.
663
                my $old_marc = MARC::Record->new_from_xml(StripNonXmlChars($oldxml), 'UTF-8', $rowref->{'encoding'}, $marc_type);
664 665 666
                foreach my $item_field ($old_marc->field($item_tag)) {
                    $old_marc->delete_field($item_field);
                }
667
                $oldxml = $old_marc->as_xml($marc_type);
668

669
                ModBiblio($marc_record, $recordid, $oldbiblio->frameworkcode);
670 671
                $query = "UPDATE import_biblios SET matched_biblionumber = ? WHERE import_record_id = ?";

672 673
                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);
674
                    $num_items_added += $bib_items_added;
675
                    $num_items_replaced += $bib_items_replaced;
676 677 678
                    $num_items_errored += $bib_items_errored;
                }
            } else {
679
                $oldxml = GetAuthorityXML($recordid);
680

681 682 683
                ModAuthority($recordid, $marc_record, GuessAuthTypeCode($marc_record));
                $query = "UPDATE import_auths SET matched_authid = ? WHERE import_record_id = ?";
            }
684
            my $sth = $dbh->prepare_cached("UPDATE import_records SET marcxml_old = ? WHERE import_record_id = ?");
685
            $sth->execute($oldxml, $rowref->{'import_record_id'});
686
            $sth->finish();
687 688
            my $sth2 = $dbh->prepare_cached($query);
            $sth2->execute($recordid, $rowref->{'import_record_id'});
689
            $sth2->finish();
690
            SetImportRecordOverlayStatus($rowref->{'import_record_id'}, 'match_applied');
691
            SetImportRecordStatus($rowref->{'import_record_id'}, 'imported');
692
        } elsif ($record_result eq 'ignore') {
693
            $recordid = $record_match;
694
            $num_ignored++;
695
            $recordid = $record_match;
696
            if ($record_type eq 'biblio' and defined $recordid and ( $item_result eq 'create_new' || $item_result eq 'replace' ) ) {
697
                my ($bib_items_added, $bib_items_replaced, $bib_items_errored) = BatchCommitItems($rowref->{'import_record_id'}, $recordid, $item_result);
698
                $num_items_added += $bib_items_added;
699
         $num_items_replaced += $bib_items_replaced;
700 701 702 703
                $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 = ?");
704
                $sth2->execute($recordid, $rowref->{'import_record_id'});
705 706 707
                SetImportRecordOverlayStatus($rowref->{'import_record_id'}, 'match_applied');
            }
            SetImportRecordStatus($rowref->{'import_record_id'}, 'ignored');
708 709 710
        }
    }
    $sth->finish();
711
    SetImportBatchStatus($batch_id, 'imported');
712
    return ($num_added, $num_updated, $num_items_added, $num_items_replaced, $num_items_errored, $num_ignored);
713 714 715 716
}

=head2 BatchCommitItems

Andrew Elwell's avatar
Andrew Elwell committed
717 718
  ($num_items_added, $num_items_errored) = 
         BatchCommitItems($import_record_id, $biblionumber);
719 720 721 722

=cut

sub BatchCommitItems {
723
    my ( $import_record_id, $biblionumber, $action ) = @_;
724 725 726

    my $dbh = C4::Context->dbh;

727 728 729 730
    my $num_items_added = 0;
    my $num_items_errored = 0;
    my $num_items_replaced = 0;

731
    my $sth = $dbh->prepare( "
732 733 734 735 736
        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
737
    " );
738
    $sth->bind_param( 1, $import_record_id );
739
    $sth->execute();
740

741 742 743
    while ( my $row = $sth->fetchrow_hashref() ) {
        my $item_marc = MARC::Record->new_from_xml( StripNonXmlChars( $row->{'marcxml'} ), 'UTF-8', $row->{'encoding'} );

744
        # Delete date_due subfield as to not accidentally delete item checkout due dates
745 746 747
        my ( $MARCfield, $MARCsubfield ) = GetMarcFromKohaField( 'items.onloan', GetFrameworkCode($biblionumber) );
        $item_marc->field($MARCfield)->delete_subfield( code => $MARCsubfield );

748
        my $item = TransformMarcToKoha( $item_marc );
749 750 751 752 753 754

        my $duplicate_barcode = exists( $item->{'barcode'} ) && GetItemnumberFromBarcode( $item->{'barcode'} );
        my $duplicate_itemnumber = exists( $item->{'itemnumber'} );

        my $updsth = $dbh->prepare("UPDATE import_items SET status = ?, itemnumber = ? WHERE import_items_id = ?");
        if ( $action eq "replace" && $duplicate_itemnumber ) {
755
            # Duplicate itemnumbers have precedence, that way we can update barcodes by overlaying
756 757 758 759
            ModItemFromMarc( $item_marc, $biblionumber, $item->{itemnumber} );
            $updsth->bind_param( 1, 'imported' );
            $updsth->bind_param( 2, $item->{itemnumber} );
            $updsth->bind_param( 3, $row->{'import_items_id'} );
760 761
            $updsth->execute();
            $updsth->finish();
762
            $num_items_replaced++;
763 764 765 766 767 768 769 770 771
        } elsif ( $action eq "replace" && $duplicate_barcode ) {
            my $itemnumber = GetItemnumberFromBarcode( $item->{'barcode'} );
            ModItemFromMarc( $item_marc, $biblionumber, $itemnumber );
            $updsth->bind_param( 1, 'imported' );
            $updsth->bind_param( 2, $item->{itemnumber} );
            $updsth->bind_param( 3, $row->{'import_items_id'} );
            $updsth->execute();
            $updsth->finish();
            $num_items_replaced++;
772 773 774 775
        } elsif ($duplicate_barcode) {
            $updsth->bind_param( 1, 'error' );
            $updsth->bind_param( 2, 'duplicate item barcode' );
            $updsth->bind_param( 3, $row->{'import_items_id'} );
776 777 778
            $updsth->execute();
            $num_items_errored++;
        } else {
779
            my ( $item_biblionumber, $biblioitemnumber, $itemnumber ) = AddItemFromMarc( $item_marc, $biblionumber );
780 781 782 783 784 785 786 787
            if( $itemnumber ) {
                $updsth->bind_param( 1, 'imported' );
                $updsth->bind_param( 2, $itemnumber );
                $updsth->bind_param( 3, $row->{'import_items_id'} );
                $updsth->execute();
                $updsth->finish();
                $num_items_added++;
            }
788
        }
789
    }
790 791

    return ( $num_items_added, $num_items_replaced, $num_items_errored );
792 793
}

794
=head2 BatchRevertRecords
795

Andrew Elwell's avatar
Andrew Elwell committed
796
  my ($num_deleted, $num_errors, $num_reverted, $num_items_deleted, 
797
      $num_ignored) = BatchRevertRecords($batch_id);
798 799 800

=cut

801
sub BatchRevertRecords {
802 803
    my $batch_id = shift;

804 805
    $logger->trace("C4::ImportBatch::BatchRevertRecords( $batch_id )");

806
    my $record_type;
807 808 809 810
    my $num_deleted = 0;
    my $num_errors = 0;
    my $num_reverted = 0;
    my $num_ignored = 0;
811
    my $num_items_deleted = 0;
812 813 814
    # commit (i.e., save, all records in the batch)
    SetImportBatchStatus('reverting');
    my $overlay_action = GetImportBatchOverlayAction($batch_id);
815
    my $nomatch_action = GetImportBatchNoMatchAction($batch_id);
816
    my $dbh = C4::Context->dbh;
817
    my $sth = $dbh->prepare("SELECT import_records.import_record_id, record_type, status, overlay_status, marcxml_old, encoding, matched_biblionumber, matched_authid
818
                             FROM import_records
819 820
                             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)
821 822
                             WHERE import_batch_id = ?");
    $sth->execute($batch_id);
823 824
    my $marc_type;
    my $marcflavour = C4::Context->preference('marcflavour');
825
    while (my $rowref = $sth->fetchrow_hashref) {
826
        $record_type = $rowref->{'record_type'};
827 828
        if ($rowref->{'status'} eq 'error' or $rowref->{'status'} eq 'reverted') {
            $num_ignored++;
829
            next;
830
        }
831 832 833 834 835 836 837
        if ($marcflavour eq 'UNIMARC' && $record_type eq 'auth') {
            $marc_type = 'UNIMARCAUTH';
        } elsif ($marcflavour eq 'UNIMARC') {
            $marc_type = 'UNIMARC';
        } else {
            $marc_type = 'USMARC';
        }
838

839
        my $record_result = _get_revert_action($overlay_action, $rowref->{'overlay_status'}, $rowref->{'status'});
840

841 842 843 844 845 846
        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 {
847
                DelAuthority({ authid => $rowref->{'matched_authid'} });
848
            }
849 850 851 852 853 854
            if (defined $error) {
                $num_errors++;
            } else {
                $num_deleted++;
                SetImportRecordStatus($rowref->{'import_record_id'}, 'reverted');
            }
855
        } elsif ($record_result eq 'restore') {
856
            $num_reverted++;
857
            my $old_record = MARC::Record->new_from_xml(StripNonXmlChars($rowref->{'marcxml_old'}), 'UTF-8', $rowref->{'encoding'}, $marc_type);
858 859
            if ($record_type eq 'biblio') {
                my $biblionumber = $rowref->{'matched_biblionumber'};
860
                my $oldbiblio = Koha::Biblios->find( $biblionumber );
861

862
                $logger->info("C4::ImportBatch::BatchRevertRecords: Biblio record $biblionumber does not exist, restoration of this record was skipped") unless $oldbiblio;
863 864
                next unless $oldbiblio; # Record has since been deleted. Deleted records should stay deleted.

865
                $num_items_deleted += BatchRevertItems($rowref->{'import_record_id'}, $rowref->{'matched_biblionumber'});
866
                ModBiblio($old_record, $biblionumber, $oldbiblio->frameworkcode);
867 868 869 870
            } else {
                my $authid = $rowref->{'matched_authid'};
                ModAuthority($authid, $old_record, GuessAuthTypeCode($old_record));
            }
871
            SetImportRecordStatus($rowref->{'import_record_id'}, 'reverted');
872 873 874 875
        } elsif ($record_result eq 'ignore') {
            if ($record_type eq 'biblio') {
                $num_items_deleted += BatchRevertItems($rowref->{'import_record_id'}, $rowref->{'matched_biblionumber'});
            }
876
            SetImportRecordStatus($rowref->{'import_record_id'}, 'reverted');
877
        }
878 879 880 881 882 883 884 885 886
        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 = ?";
            $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);
Galen Charlton's avatar
Galen Charlton committed
887
        $sth2->execute($rowref->{'import_record_id'});
888
    }
889

890 891
    $sth->finish();
    SetImportBatchStatus($batch_id, 'reverted');
892 893 894 895 896
    return ($num_deleted, $num_errors, $num_reverted, $num_items_deleted, $num_ignored);
}

=head2 BatchRevertItems

Andrew Elwell's avatar
Andrew Elwell committed
897
  my $num_items_deleted = BatchRevertItems($import_record_id, $biblionumber);
898 899 900 901 902 903 904 905 906 907 908

=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
909
                                   JOIN items USING (itemnumber)
910 911 912 913
                                   WHERE import_record_id = ?");
    $sth->bind_param(1, $import_record_id);
    $sth->execute();
    while (my $row = $sth->fetchrow_hashref()) {
914
        my $error = DelItemCheck( $biblionumber, $row->{'itemnumber'});
915 916 917 918 919 920 921 922 923 924 925
        if ($error == 1){
            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;
        }
926 927 928
    }
    $sth->finish();
    return $num_items_deleted;
929 930
}

931 932
=head2 CleanBatch

Andrew Elwell's avatar
Andrew Elwell committed
933
  CleanBatch($batch_id)
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949

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');
}

950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967
=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 );
}

968 969
=head2 GetAllImportBatches

Andrew Elwell's avatar
Andrew Elwell committed
970
  my $results = GetAllImportBatches();
971 972 973 974 975 976 977 978 979 980

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
981
                                    WHERE batch_type IN ('batch', 'webservice')
982 983 984 985 986 987 988 989 990 991 992
                                    ORDER BY import_batch_id ASC");

    my $results = [];
    $sth->execute();
    while (my $row = $sth->fetchrow_hashref) {
        push @$results, $row;
    }
    $sth->finish();
    return $results;
}

993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
=head2 GetStagedWebserviceBatches

  my $batch_ids = GetStagedWebserviceBatches();

Returns a references to an array of batch id's
of batch_type 'webservice' that are not imported

=cut

my $PENDING_WEBSERVICE_BATCHES_QRY = <<EOQ;
SELECT import_batch_id FROM import_batches
WHERE batch_type = 'webservice'
AND import_status = 'staged'
EOQ
sub  GetStagedWebserviceBatches {
    my $dbh = C4::Context->dbh;
    return $dbh->selectcol_arrayref($PENDING_WEBSERVICE_BATCHES_QRY);
}

1012 1013
=head2 GetImportBatchRangeDesc

Andrew Elwell's avatar
Andrew Elwell committed
1014
  my $results = GetImportBatchRangeDesc($offset, $results_per_group);
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025

Returns a reference to an array of hash references corresponding to
import_batches rows (sorted in descending order by import_batch_id)
start at the given offset.

=cut

sub GetImportBatchRangeDesc {
    my ($offset, $results_per_group) = @_;

    my $dbh = C4::Context->dbh;
Paul Poulain's avatar
Paul Poulain committed
1026
    my $query = "SELECT * FROM import_batches
1027
                                    WHERE batch_type IN ('batch', 'webservice')
Paul Poulain's avatar
Paul Poulain committed
1028 1029
                                    ORDER BY import_batch_id DESC";
    my @params;
1030 1031 1032 1033
    if ($results_per_group){
        $query .= " LIMIT ?";
        push(@params, $results_per_group);
    }
Paul Poulain's avatar
Paul Poulain committed
1034 1035 1036
    if ($offset){
        $query .= " OFFSET ?";
        push(@params, $offset);
1037
    }
Paul Poulain's avatar
Paul Poulain committed
1038 1039 1040
    my $sth = $dbh->prepare_cached($query);
    $sth->execute(@params);
    my $results = $sth->fetchall_arrayref({});
1041 1042 1043 1044
    $sth->finish();
    return $results;
}

1045 1046
=head2 GetItemNumbersFromImportBatch

Andrew Elwell's avatar
Andrew Elwell committed
1047 1048
  my @itemsnos = GetItemNumbersFromImportBatch($batch_id);

1049 1050 1051
=cut

sub GetItemNumbersFromImportBatch {
1052 1053
    my ($batch_id) = @_;
    my $dbh = C4::Context->dbh;
1054 1055 1056 1057 1058 1059
    my $sql = q|
SELECT itemnumber FROM import_items
INNER JOIN items USING (itemnumber)
INNER JOIN import_records USING (import_record_id)
WHERE import_batch_id = ?|;
    my  $sth = $dbh->prepare( $sql );
1060 1061 1062 1063 1064 1065
    $sth->execute($batch_id);
    my @items ;
    while ( my ($itm) = $sth->fetchrow_array ) {
        push @items, $itm;
    }
    return @items;
1066 1067
}

1068
=head2 GetNumberOfImportBatches
1069

Andrew Elwell's avatar
Andrew Elwell committed
1070
  my $count = GetNumberOfImportBatches();
1071 1072 1073 1074 1075

=cut

sub GetNumberOfNonZ3950ImportBatches {
    my $dbh = C4::Context->dbh;
1076
    my $sth = $dbh->prepare("SELECT COUNT(*) FROM import_batches WHERE batch_type != 'z3950'");
1077 1078 1079 1080 1081 1082
    $sth->execute();
    my ($count) = $sth->fetchrow_array();
    $sth->finish();
    return $count;
}

1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
=head2 GetImportBiblios

  my $results = GetImportBiblios($importid);

=cut

sub GetImportBiblios {
    my ($import_record_id) = @_;

    my $dbh = C4::Context->dbh;
    my $query = "SELECT * FROM import_biblios WHERE import_record_id = ?";
1094 1095 1096 1097 1098
    return $dbh->selectall_arrayref(
        $query,
        { Slice => {} },
        $import_record_id
    );
1099 1100 1101

}

1102
=head2 GetImportRecordsRange
1103

1104
  my $results = GetImportRecordsRange($batch_id, $offset, $results_per_group);
1105 1106

Returns a reference to an array of hash references corresponding to
1107
import_biblios/import_auths/import_records rows for a given batch
1108 1109 1110 1111
starting at the given offset.

=cut

1112
sub GetImportRecordsRange {
1113
    my ( $batch_id, $offset, $results_per_group, $status, $parameters ) = @_;
1114 1115

    my $dbh = C4::Context->dbh;
1116

Kyle M Hall's avatar
Kyle M Hall committed
1117 1118 1119
    my $order_by = $parameters->{order_by} || 'import_record_id';
    ( $order_by ) = grep( /^$order_by$/, qw( import_record_id title status overlay_status ) ) ? $order_by : 'import_record_id';

1120
    my $order_by_direction =
1121
      uc( $parameters->{order_by_direction} // 'ASC' ) eq 'DESC' ? 'DESC' : 'ASC';
1122

1123 1124
    $order_by .= " $order_by_direction, authorized_heading" if $order_by eq 'title';

1125 1126 1127
    my $query = "SELECT title, author, isbn, issn, authorized_heading, import_records.import_record_id,
                                           record_sequence, status, overlay_status,
                                           matched_biblionumber, matched_authid, record_type
1128
                                    FROM   import_records
1129 1130
                                    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)
1131
                                    WHERE  import_batch_id = ?";
Paul Poulain's avatar
Paul Poulain committed
1132 1133
    my @params;
    push(@params, $batch_id);
1134 1135 1136 1137
    if ($status) {
        $query .= " AND status=?";
        push(@params,$status);
    }
1138 1139

    $query.=" ORDER BY $order_by $order_by_direction";
1140

1141 1142 1143 1144
    if($results_per_group){
        $query .= " LIMIT ?";
        push(@params, $results_per_group);
    }
Paul Poulain's avatar
Paul Poulain committed
1145 1146 1147
    if($offset){
        $query .= " OFFSET ?";
        push(@params, $offset);
1148
    }
Paul Poulain's avatar
Paul Poulain committed
1149 1150 1151
    my $sth = $dbh->prepare_cached($query);
    $sth->execute(@params);
    my $results = $sth->fetchall_arrayref({});
1152 1153 1154 1155 1156
    $sth->finish();
    return $results;

}

1157 1158
=head2 GetBestRecordMatch

Andrew Elwell's avatar
Andrew Elwell committed
1159
  my $record_id = GetBestRecordMatch($import_record_id);
1160 1161 1162 1163 1164 1165 1166 1167 1168

=cut

sub GetBestRecordMatch {
    my ($import_record_id) = @_;

    my $dbh = C4::Context->dbh;
    my $sth = $dbh->prepare("SELECT candidate_match_id
                             FROM   import_record_matches
1169 1170 1171 1172 1173 1174
                             JOIN   import_records ON ( import_record_matches.import_record_id = import_records.import_record_id )
                             LEFT JOIN biblio ON ( candidate_match_id = biblio.biblionumber )
                             LEFT JOIN auth_header ON ( candidate_match_id = auth_header.authid )
                             WHERE  import_record_matches.import_record_id = ? AND
                             (  (import_records.record_type = 'biblio' AND biblio.biblionumber IS NOT NULL) OR
                                (import_records.record_type = 'auth' AND auth_header.authid IS NOT NULL) )
1175 1176 1177 1178 1179 1180 1181 1182 1183
                             ORDER BY score DESC, candidate_match_id DESC");
    $sth->execute($import_record_id);
    my ($record_id) = $sth->fetchrow_array();
    $sth->finish();
    return $record_id;
}

=head2 GetImportBatchStatus

Andrew Elwell's avatar
Andrew Elwell committed
1184
  my $status = GetImportBatchStatus($batch_id);
1185 1186 1187 1188 1189 1190 1191

=cut

sub GetImportBatchStatus {
    my ($batch_id) = @_;

    my $dbh = C4::Context->dbh;
1192
    my $sth = $dbh->prepare("SELECT import_status FROM import_batches WHERE import_batch_id = ?");
1193 1194 1195
    $sth->execute($batch_id);
    my ($status) = $sth->fetchrow_array();
    $sth->finish();
1196
    return $status;
1197 1198 1199 1200 1201

}

=head2 SetImportBatchStatus

Andrew Elwell's avatar
Andrew Elwell committed
1202
  SetImportBatchStatus($batch_id, $new_status);
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217

=cut

sub SetImportBatchStatus {
    my ($batch_id, $new_status) = @_;

    my $dbh = C4::Context->dbh;
    my $sth = $dbh->prepare("UPDATE import_batches SET import_status = ? WHERE import_batch_id = ?");
    $sth->execute($new_status, $batch_id);
    $sth->finish();

}

=head2 GetImportBatchOverlayAction

Andrew Elwell's avatar
Andrew Elwell committed
1218
  my $overlay_action = GetImportBatchOverlayAction($batch_id);
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236

=cut

sub GetImportBatchOverlayAction {
    my ($batch_id) = @_;

    my $dbh = C4::Context->dbh;
    my $sth = $dbh->prepare("SELECT overlay_action FROM import_batches WHERE import_batch_id = ?");
    $sth->execute($batch_id);
    my ($overlay_action) = $sth->fetchrow_array();
    $sth->finish();
    return $overlay_action;

}


=head2 SetImportBatchOverlayAction

Andrew Elwell's avatar
Andrew Elwell committed
1237
  SetImportBatchOverlayAction($batch_id, $new_overlay_action);
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250

=cut

sub SetImportBatchOverlayAction {
    my ($batch_id, $new_overlay_action) = @_;

    my $dbh = C4::Context->dbh;
    my $sth = $dbh->prepare("UPDATE import_batches SET overlay_action = ? WHERE import_batch_id = ?");
    $sth->execute($new_overlay_action, $batch_id);
    $sth->finish();

}

1251 1252
=head2 GetImportBatchNoMatchAction

Andrew Elwell's avatar
Andrew Elwell committed
1253
  my $nomatch_action = GetImportBatchNoMatchAction($batch_id);
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271

=cut

sub GetImportBatchNoMatchAction {
    my ($batch_id) = @_;

    my $dbh = C4::Context->dbh;
    my $sth = $dbh->prepare("SELECT nomatch_action FROM import_batches WHERE import_batch_id = ?");
    $sth->execute($batch_id);
    my ($nomatch_action) = $sth->fetchrow_array();
    $sth->finish();
    return $nomatch_action;

}


=head2 SetImportBatchNoMatchAction

Andrew Elwell's avatar
Andrew Elwell committed
1272
  SetImportBatchNoMatchAction($batch_id, $new_nomatch_action);
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287

=cut

sub SetImportBatchNoMatchAction {
    my ($batch_id, $new_nomatch_action) = @_;

    my $dbh = C4::Context->dbh;
    my $sth = $dbh->prepare("UPDATE import_batches SET nomatch_action = ? WHERE import_batch_id = ?");
    $sth->execute($new_nomatch_action, $batch_id);
    $sth->finish();

}

=head2 GetImportBatchItemAction

Andrew Elwell's avatar
Andrew Elwell committed
1288
  my $item_action = GetImportBatchItemAction($batch_id);
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306

=cut

sub GetImportBatchItemAction {
    my ($batch_id) = @_;

    my $dbh = C4::Context->dbh;
    my $sth = $dbh->prepare("SELECT item_action FROM import_batches WHERE import_batch_id = ?");
    $sth->execute($batch_id);
    my ($item_action) = $sth->fetchrow_array();
    $sth->finish();
    return $item_action;

}


=head2 SetImportBatchItemAction

Andrew Elwell's avatar
Andrew Elwell committed
1307
  SetImportBatchItemAction($batch_id, $new_item_action);
1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320

=cut

sub SetImportBatchItemAction {
    my ($batch_id, $new_item_action) = @_;

    my $dbh = C4::Context->dbh;
    my $sth = $dbh->prepare("UPDATE import_batches SET item_action = ? WHERE import_batch_id = ?");
    $sth->execute($new_item_action, $batch_id);
    $sth->finish();

}

1321 1322
=head2 GetImportBatchMatcher

Andrew Elwell's avatar
Andrew Elwell committed
1323
  my $matcher_id = GetImportBatchMatcher($batch_id);
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341

=cut

sub GetImportBatchMatcher {
    my ($batch_id) = @_;

    my $dbh = C4::Context->dbh;
    my $sth = $dbh->prepare("SELECT matcher_id FROM import_batches WHERE import_batch_id = ?");
    $sth->execute($batch_id);
    my ($matcher_id) = $sth->fetchrow_array();
    $sth->finish();
    return $matcher_id;

}


=head2 SetImportBatchMatcher

Andrew Elwell's avatar
Andrew Elwell committed
1342
  SetImportBatchMatcher($batch_id, $new_matcher_id);
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355

=cut

sub SetImportBatchMatcher {
    my ($batch_id, $new_matcher_id) = @_;

    my $dbh = C4::Context->dbh;
    my $sth = $dbh->prepare("UPDATE import_batches SET matcher_id = ? WHERE import_batch_id = ?");
    $sth->execute($new_matcher_id, $batch_id);
    $sth->finish();

}

1356 1357
=head2 GetImportRecordOverlayStatus

Andrew Elwell's avatar
Andrew Elwell committed
1358
  my $overlay_status = GetImportRecordOverlayStatus($import_record_id);
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376

=cut

sub GetImportRecordOverlayStatus {
    my ($import_record_id) = @_;

    my $dbh = C4::Context->dbh;
    my $sth = $dbh->prepare("SELECT overlay_status FROM import_records WHERE import_record_id = ?");
    $sth->execute($import_record_id);
    my ($overlay_status) = $sth->fetchrow_array();
    $sth->finish();
    return $overlay_status;

}


=head2 SetImportRecordOverlayStatus

Andrew Elwell's avatar
Andrew Elwell committed
1377
  SetImportRecordOverlayStatus($import_record_id, $new_overlay_status);
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390

=cut

sub SetImportRecordOverlayStatus {
    my ($import_record_id, $new_overlay_status) = @_;

    my $dbh = C4::Context->dbh;
    my $sth = $dbh->prepare("UPDATE import_records SET overlay_status = ? WHERE import_record_id = ?");
    $sth->execute($new_overlay_status, $import_record_id);
    $sth->finish();

}

1391 1392
=head2 GetImportRecordStatus

1393
  my $status = GetImportRecordStatus($import_record_id);
1394 1395 1396 1397 1398 1399 1400 1401 1402

=cut

sub GetImportRecordStatus {
    my ($import_record_id) = @_;

    my $dbh = C4::Context->dbh;
    my $sth = $dbh->prepare("SELECT status FROM import_records WHERE import_record_id = ?");
    $sth->execute($import_record_id);
1403
    my ($status) = $sth->fetchrow_array();
1404
    $sth->finish();
1405
    return $status;
1406 1407 1408 1409 1410 1411

}


=head2 SetImportRecordStatus

1412
  SetImportRecordStatus($import_record_id, $new_status);
1413 1414 1415 1416

=cut

sub SetImportRecordStatus {
1417
    my ($import_record_id, $new_status) = @_;
1418 1419 1420

    my $dbh = C4::Context->dbh;
    my $sth = $dbh->prepare("UPDATE import_records SET status = ? WHERE import_record_id = ?");
1421
    $sth->execute($new_status, $impo