staged MARC import: handle non-ASCII characters in items
[koha.git] / C4 / ImportBatch.pm
1 package C4::ImportBatch;
2
3 # Copyright (C) 2007 LibLime
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA  02111-1307 USA
19
20 use strict;
21 use C4::Context;
22 use C4::Koha;
23 use C4::Biblio;
24 use C4::Items;
25
26 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
27
28 BEGIN {
29         # set the version for version checking
30         $VERSION = 3.01;
31         require Exporter;
32         @ISA    = qw(Exporter);
33         @EXPORT = qw(
34     GetZ3950BatchId
35     GetImportRecordMarc
36     AddImportBatch
37     GetImportBatch
38     AddBiblioToBatch
39     ModBiblioInBatch
40
41     BatchStageMarcRecords
42     BatchFindBibDuplicates
43     BatchCommitBibRecords
44     BatchRevertBibRecords
45
46     GetAllImportBatches
47     GetImportBatchRangeDesc
48     GetNumberOfNonZ3950ImportBatches
49     GetImportBibliosRange
50     
51     GetImportBatchStatus
52     SetImportBatchStatus
53     GetImportBatchOverlayAction
54     SetImportBatchOverlayAction
55     GetImportBatchMatcher
56     SetImportBatchMatcher
57     GetImportRecordOverlayStatus
58     SetImportRecordOverlayStatus
59     GetImportRecordStatus
60     SetImportRecordStatus
61     GetImportRecordMatches
62     SetImportRecordMatches
63         );
64 }
65
66 =head1 NAME
67
68 C4::ImportBatch - manage batches of imported MARC records
69
70 =head1 SYNOPSIS
71
72 =over 4
73
74 use C4::ImportBatch;
75
76 =back
77
78 =head1 FUNCTIONS
79
80 =head2 GetZ3950BatchId
81
82 =over 4
83
84 my $batchid = GetZ3950BatchId($z3950server);
85
86 =back
87
88 Retrieves the ID of the import batch for the Z39.50
89 reservoir for the given target.  If necessary,
90 creates the import batch.
91
92 =cut
93
94 sub GetZ3950BatchId {
95     my ($z3950server) = @_;
96
97     my $dbh = C4::Context->dbh;
98     my $sth = $dbh->prepare("SELECT import_batch_id FROM import_batches
99                              WHERE  batch_type = 'z3950'
100                              AND    file_name = ?");
101     $sth->execute($z3950server);
102     my $rowref = $sth->fetchrow_arrayref();
103     $sth->finish();
104     if (defined $rowref) {
105         return $rowref->[0];
106     } else {
107         my $batch_id = AddImportBatch('create_new', 'staged', 'z3950', $z3950server, '');
108         return $batch_id;
109     }
110     
111 }
112
113 =head2 GetImportRecordMarc
114
115 =over 4
116
117 my ($marcblob, $encoding) = GetImportRecordMarc($import_record_id);
118
119 =back
120
121 =cut
122
123 sub GetImportRecordMarc {
124     my ($import_record_id) = @_;
125
126     my $dbh = C4::Context->dbh;
127     my $sth = $dbh->prepare("SELECT marc, encoding FROM import_records WHERE import_record_id = ?");
128     $sth->execute($import_record_id);
129     my ($marc, $encoding) = $sth->fetchrow();
130     $sth->finish();
131     return $marc;
132
133 }
134
135 =head2 AddImportBatch
136
137 =over 4
138
139 my $batch_id = AddImportBatch($overlay_action, $import_status, $type, $file_name, $comments);
140
141 =back
142
143 =cut
144
145 sub AddImportBatch {
146     my ($overlay_action, $import_status, $type, $file_name, $comments) = @_;
147
148     my $dbh = C4::Context->dbh;
149     my $sth = $dbh->prepare("INSERT INTO import_batches (overlay_action, import_status, batch_type,
150                                                          file_name, comments)
151                                     VALUES (?, ?, ?, ?, ?)");
152     $sth->execute($overlay_action, $import_status, $type, $file_name, $comments);
153     my $batch_id = $dbh->{'mysql_insertid'};
154     $sth->finish();
155
156     return $batch_id;
157
158 }
159
160 =head2 GetImportBatch 
161
162 =over 4
163
164 my $row = GetImportBatch($batch_id);
165
166 =back
167
168 Retrieve a hashref of an import_batches row.
169
170 =cut
171
172 sub GetImportBatch {
173     my ($batch_id) = @_;
174
175     my $dbh = C4::Context->dbh;
176     my $sth = $dbh->prepare_cached("SELECT * FROM import_batches WHERE import_batch_id = ?");
177     $sth->bind_param(1, $batch_id);
178     $sth->execute();
179     my $result = $sth->fetchrow_hashref;
180     $sth->finish();
181     return $result;
182
183 }
184
185 =head2 AddBiblioToBatch 
186
187 =over 4
188
189 my $import_record_id = AddBiblioToBatch($batch_id, $record_sequence, $marc_record, $encoding, $z3950random, $update_counts);
190
191 =back
192
193 =cut
194
195 sub AddBiblioToBatch {
196     my $batch_id = shift;
197     my $record_sequence = shift;
198     my $marc_record = shift;
199     my $encoding = shift;
200     my $z3950random = shift;
201     my $update_counts = @_ ? shift : 1;
202
203     my $import_record_id = _create_import_record($batch_id, $record_sequence, $marc_record, 'biblio', $encoding, $z3950random);
204     _add_biblio_fields($import_record_id, $marc_record);
205     _update_batch_record_counts($batch_id) if $update_counts;
206     return $import_record_id;
207 }
208
209 =head2 ModBiblioInBatch
210
211 =over 4
212
213 ModBiblioInBatch($import_record_id, $marc_record);
214
215 =back
216
217 =cut
218
219 sub ModBiblioInBatch {
220     my ($import_record_id, $marc_record) = @_;
221
222     _update_import_record_marc($import_record_id, $marc_record);
223     _update_biblio_fields($import_record_id, $marc_record);
224
225 }
226
227 =head2 BatchStageMarcRecords
228
229 =over 4
230
231 ($batch_id, $num_records, $num_items, @invalid_records) = 
232     BatchStageMarcRecords($marc_flavor, $marc_records, $file_name, 
233                           $comments, $branch_code, $parse_items,
234                           $leave_as_staging, 
235                           $progress_interval, $progress_callback);
236
237 =back
238
239 =cut
240
241 sub  BatchStageMarcRecords {
242     my $marc_flavor = shift;
243     my $marc_records = shift;
244     my $file_name = shift;
245     my $comments = shift;
246     my $branch_code = shift;
247     my $parse_items = shift;
248     my $leave_as_staging = shift;
249    
250     # optional callback to monitor status 
251     # of job
252     my $progress_interval = 0;
253     my $progress_callback = undef;
254     if ($#_ == 1) {
255         $progress_interval = shift;
256         $progress_callback = shift;
257         $progress_interval = 0 unless $progress_interval =~ /^\d+$/ and $progress_interval > 0;
258         $progress_interval = 0 unless 'CODE' eq ref $progress_callback;
259     } 
260     
261     my $batch_id = AddImportBatch('create_new', 'staging', 'batch', $file_name, $comments);
262     my @invalid_records = ();
263     my $num_valid = 0;
264     my $num_items = 0;
265     # FIXME - for now, we're dealing only with bibs
266     my $rec_num = 0;
267     foreach my $marc_blob (split(/\x1D/, $marc_records)) {
268         $rec_num++;
269         if ($progress_interval and (0 == ($rec_num % $progress_interval))) {
270             &$progress_callback($rec_num);
271         }
272         my $marc_record = FixEncoding($marc_blob);
273         my $import_record_id;
274         if (scalar($marc_record->fields()) == 0) {
275             push @invalid_records, $marc_blob;
276         } else {
277             $num_valid++;
278             $import_record_id = AddBiblioToBatch($batch_id, $rec_num, $marc_record, $marc_flavor, int(rand(99999)), 0);
279             if ($parse_items) {
280                 my @import_items_ids = AddItemsToImportBiblio($batch_id, $import_record_id, $marc_record, 0);
281                 $num_items += scalar(@import_items_ids);
282             }
283         }
284     }
285     unless ($leave_as_staging) {
286         SetImportBatchStatus($batch_id, 'staged');
287     }
288     # FIXME branch_code, number of bibs, number of items
289     _update_batch_record_counts($batch_id);
290     return ($batch_id, $num_valid, $num_items, @invalid_records);
291 }
292
293 =head2 AddItemsToImportBiblio
294
295 =over 4
296
297 my @import_items_ids = AddItemsToImportBiblio($batch_id, $import_record_id, $marc_record, $update_counts);
298
299 =back
300
301 =cut
302
303 sub AddItemsToImportBiblio {
304     my $batch_id = shift;
305     my $import_record_id = shift;
306     my $marc_record = shift;
307     my $update_counts = @_ ? shift : 0;
308
309     my @import_items_ids = ();
310    
311     my $dbh = C4::Context->dbh; 
312     my ($item_tag,$item_subfield) = &GetMarcFromKohaField("items.itemnumber",'');
313     foreach my $item_field ($marc_record->field($item_tag)) {
314         my $item_marc = MARC::Record->new();
315         $item_marc->leader("00000    a              "); # must set Leader/09 to 'a'
316         $item_marc->append_fields($item_field);
317         $marc_record->delete_field($item_field);
318         my $sth = $dbh->prepare_cached("INSERT INTO import_items (import_record_id, status, marcxml)
319                                         VALUES (?, ?, ?)");
320         $sth->bind_param(1, $import_record_id);
321         $sth->bind_param(2, 'staged');
322         $sth->bind_param(3, $item_marc->as_xml());
323         $sth->execute();
324         push @import_items_ids, $dbh->{'mysql_insertid'};
325         $sth->finish();
326     }
327
328     if ($#import_items_ids > -1) {
329         _update_batch_record_counts($batch_id) if $update_counts;
330         _update_import_record_marc($import_record_id, $marc_record);
331     }
332     return @import_items_ids;
333 }
334
335 =head2 BatchFindBibDuplicates
336
337 =over 4
338
339 my $num_with_matches = BatchFindBibDuplicates($batch_id, $matcher, $max_matches, $progress_interval, $progress_callback);
340
341 =back
342
343 Goes through the records loaded in the batch and attempts to 
344 find duplicates for each one.  Sets the overlay action to
345 "replace" if it was "create_new", and sets the overlay status
346 of each record to "no_match" or "auto_match" as appropriate.
347
348 The $max_matches parameter is optional; if it is not supplied,
349 it defaults to 10.
350
351 The $progress_interval and $progress_callback parameters are 
352 optional; if both are supplied, the sub referred to by
353 $progress_callback will be invoked every $progress_interval
354 records using the number of records processed as the 
355 singular argument.
356
357 =cut
358
359 sub BatchFindBibDuplicates {
360     my $batch_id = shift;
361     my $matcher = shift;
362     my $max_matches = @_ ? shift : 10;
363
364     # optional callback to monitor status 
365     # of job
366     my $progress_interval = 0;
367     my $progress_callback = undef;
368     if ($#_ == 1) {
369         $progress_interval = shift;
370         $progress_callback = shift;
371         $progress_interval = 0 unless $progress_interval =~ /^\d+$/ and $progress_interval > 0;
372         $progress_interval = 0 unless 'CODE' eq ref $progress_callback;
373     }
374
375     my $dbh = C4::Context->dbh;
376     my $old_overlay_action = GetImportBatchOverlayAction($batch_id);
377     if ($old_overlay_action eq "create_new") {
378         SetImportBatchOverlayAction($batch_id, 'replace');
379     }
380
381     my $sth = $dbh->prepare("SELECT import_record_id, marc
382                              FROM import_records
383                              JOIN import_biblios USING (import_record_id)
384                              WHERE import_batch_id = ?");
385     $sth->execute($batch_id);
386     my $num_with_matches = 0;
387     my $rec_num = 0;
388     while (my $rowref = $sth->fetchrow_hashref) {
389         $rec_num++;
390         if ($progress_interval and (0 == ($rec_num % $progress_interval))) {
391             &$progress_callback($rec_num);
392         }
393         my $marc_record = MARC::Record->new_from_usmarc($rowref->{'marc'});
394         my @matches = ();
395         if (defined $matcher) {
396             @matches = $matcher->get_matches($marc_record, $max_matches);
397         }
398         if (scalar(@matches) > 0) {
399             $num_with_matches++;
400             SetImportRecordMatches($rowref->{'import_record_id'}, @matches);
401             SetImportRecordOverlayStatus($rowref->{'import_record_id'}, 'auto_match');
402         } else {
403             SetImportRecordMatches($rowref->{'import_record_id'}, ());
404             SetImportRecordOverlayStatus($rowref->{'import_record_id'}, 'no_match');
405         }
406     }
407     $sth->finish();
408     return $num_with_matches;
409 }
410
411 =head2 BatchCommitBibRecords
412
413 =over 4
414
415 my ($num_added, $num_updated, $num_items_added, $num_items_errored, $num_ignored) = 
416     BatchCommitBibRecords($batch_id, $progress_interval, $progress_callback);
417
418 =back
419
420 =cut
421
422 sub BatchCommitBibRecords {
423     my $batch_id = shift;
424
425     # optional callback to monitor status 
426     # of job
427     my $progress_interval = 0;
428     my $progress_callback = undef;
429     if ($#_ == 1) {
430         $progress_interval = shift;
431         $progress_callback = shift;
432         $progress_interval = 0 unless $progress_interval =~ /^\d+$/ and $progress_interval > 0;
433         $progress_interval = 0 unless 'CODE' eq ref $progress_callback;
434     }
435
436     my $num_added = 0;
437     my $num_updated = 0;
438     my $num_items_added = 0;
439     my $num_items_errored = 0;
440     my $num_ignored = 0;
441     # commit (i.e., save, all records in the batch)
442     # FIXME biblio only at the moment
443     SetImportBatchStatus('importing');
444     my $overlay_action = GetImportBatchOverlayAction($batch_id);
445     my $dbh = C4::Context->dbh;
446     my $sth = $dbh->prepare("SELECT import_record_id, status, overlay_status, marc, encoding
447                              FROM import_records
448                              JOIN import_biblios USING (import_record_id)
449                              WHERE import_batch_id = ?");
450     $sth->execute($batch_id);
451     my $rec_num = 0;
452     while (my $rowref = $sth->fetchrow_hashref) {
453         $rec_num++;
454         if ($progress_interval and (0 == ($rec_num % $progress_interval))) {
455             &$progress_callback($rec_num);
456         }
457         if ($rowref->{'status'} eq 'error' or $rowref->{'status'} eq 'imported') {
458             $num_ignored++;
459         }
460
461         my $marc_record = MARC::Record->new_from_usmarc($rowref->{'marc'});
462
463         # remove any item tags - rely on BatchCommitItems
464         my ($item_tag,$item_subfield) = &GetMarcFromKohaField("items.itemnumber",'');
465         foreach my $item_field ($marc_record->field($item_tag)) {
466             $marc_record->delete_field($item_field);
467         }
468
469         if ($overlay_action eq 'create_new' or
470             ($overlay_action eq 'replace' and $rowref->{'overlay_status'} eq 'no_match')) {
471             $num_added++;
472             my ($biblionumber, $biblioitemnumber) = AddBiblio($marc_record, '');
473             my $sth = $dbh->prepare_cached("UPDATE import_biblios SET matched_biblionumber = ? WHERE import_record_id = ?");
474             $sth->execute($biblionumber, $rowref->{'import_record_id'});
475             $sth->finish();
476             my ($bib_items_added, $bib_items_errored) = BatchCommitItems($rowref->{'import_record_id'}, $biblionumber);
477             $num_items_added += $bib_items_added;
478             $num_items_errored += $bib_items_errored;
479             SetImportRecordStatus($rowref->{'import_record_id'}, 'imported');
480         } else {
481             $num_updated++;
482             my $biblionumber = GetBestRecordMatch($rowref->{'import_record_id'});
483             my ($count, $oldbiblio) = GetBiblio($biblionumber);
484             my $oldxml = GetXmlBiblio($biblionumber);
485
486             # remove item fields so that they don't get
487             # added again if record is reverted
488             my $old_marc = MARC::Record->new_from_xml($oldxml, 'UTF-8', $rowref->{'encoding'});
489             foreach my $item_field ($old_marc->field($item_tag)) {
490                 $old_marc->delete_field($item_field);
491             }
492
493             ModBiblio($marc_record, $biblionumber, $oldbiblio->{'frameworkcode'});
494             my $sth = $dbh->prepare_cached("UPDATE import_records SET marcxml_old = ? WHERE import_record_id = ?");
495             $sth->execute($old_marc->as_xml(), $rowref->{'import_record_id'});
496             $sth->finish();
497             my $sth2 = $dbh->prepare_cached("UPDATE import_biblios SET matched_biblionumber = ? WHERE import_record_id = ?");
498             $sth2->execute($biblionumber, $rowref->{'import_record_id'});
499             $sth2->finish();
500             my ($bib_items_added, $bib_items_errored) = BatchCommitItems($rowref->{'import_record_id'}, $biblionumber);
501             $num_items_added += $bib_items_added;
502             $num_items_errored += $bib_items_errored;
503             SetImportRecordOverlayStatus($rowref->{'import_record_id'}, 'match_applied');
504             SetImportRecordStatus($rowref->{'import_record_id'}, 'imported');
505         }
506     }
507     $sth->finish();
508     SetImportBatchStatus($batch_id, 'imported');
509     return ($num_added, $num_updated, $num_items_added, $num_items_errored, $num_ignored);
510 }
511
512 =head2 BatchCommitItems
513
514 =over 4
515
516 ($num_items_added, $num_items_errored) = BatchCommitItems($import_record_id, $biblionumber);
517
518 =back
519
520 =cut
521
522 sub BatchCommitItems {
523     my ($import_record_id, $biblionumber) = @_;
524
525     my $dbh = C4::Context->dbh;
526
527     my $num_items_added = 0;
528     my $num_items_errored = 0;
529     my $sth = $dbh->prepare("SELECT import_items_id, import_items.marcxml, encoding
530                              FROM import_items
531                              JOIN import_records USING (import_record_id)
532                              WHERE import_record_id = ?
533                              ORDER BY import_items_id");
534     $sth->bind_param(1, $import_record_id);
535     $sth->execute();
536     while (my $row = $sth->fetchrow_hashref()) {
537         my $item_marc = MARC::Record->new_from_xml($row->{'marcxml'}, 'UTF-8', $row->{'encoding'});
538         # FIXME - duplicate barcode check needs to become part of AddItemFromMarc()
539         my $item = TransformMarcToKoha($dbh, $item_marc);
540         my $duplicate_barcode = exists($item->{'barcode'}) && GetItemnumberFromBarcode($item->{'barcode'});
541         if ($duplicate_barcode) {
542             my $updsth = $dbh->prepare("UPDATE import_items SET status = ?, import_error = ? WHERE import_items_id = ?");
543             $updsth->bind_param(1, 'error');
544             $updsth->bind_param(2, 'duplicate item barcode');
545             $updsth->bind_param(3, $row->{'import_items_id'});
546             $updsth->execute();
547             $num_items_errored++;
548         } else {
549             my ($item_biblionumber, $biblioitemnumber, $itemnumber) = AddItemFromMarc($item_marc, $biblionumber);
550             my $updsth = $dbh->prepare("UPDATE import_items SET status = ?, itemnumber = ? WHERE import_items_id = ?");
551             $updsth->bind_param(1, 'imported');
552             $updsth->bind_param(2, $itemnumber);
553             $updsth->bind_param(3, $row->{'import_items_id'});
554             $updsth->execute();
555             $updsth->finish();
556             $num_items_added++;
557         }
558     }
559     $sth->finish();
560     return ($num_items_added, $num_items_errored);
561 }
562
563 =head2 BatchRevertBibRecords
564
565 =over 4
566
567 my ($num_deleted, $num_errors, $num_reverted, $num_items_deleted, $num_ignored) = BatchRevertBibRecords($batch_id);
568
569 =back
570
571 =cut
572
573 sub BatchRevertBibRecords {
574     my $batch_id = shift;
575
576     my $num_deleted = 0;
577     my $num_errors = 0;
578     my $num_reverted = 0;
579     my $num_items_deleted = 0;
580     my $num_ignored = 0;
581     # commit (i.e., save, all records in the batch)
582     # FIXME biblio only at the moment
583     SetImportBatchStatus('reverting');
584     my $overlay_action = GetImportBatchOverlayAction($batch_id);
585     my $dbh = C4::Context->dbh;
586     my $sth = $dbh->prepare("SELECT import_record_id, status, overlay_status, marcxml_old, encoding, matched_biblionumber
587                              FROM import_records
588                              JOIN import_biblios USING (import_record_id)
589                              WHERE import_batch_id = ?");
590     $sth->execute($batch_id);
591     while (my $rowref = $sth->fetchrow_hashref) {
592         if ($rowref->{'status'} eq 'error' or $rowref->{'status'} eq 'reverted') {
593             $num_ignored++;
594         }
595         if ($overlay_action eq 'create_new' or
596             ($overlay_action eq 'replace' and $rowref->{'overlay_status'} eq 'no_match')) {
597             $num_items_deleted += BatchRevertItems($rowref->{'import_record_id'}, $rowref->{'matched_biblionumber'});
598             my $error = DelBiblio($rowref->{'matched_biblionumber'});
599             if (defined $error) {
600                 $num_errors++;
601             } else {
602                 $num_deleted++;
603                 SetImportRecordStatus($rowref->{'import_record_id'}, 'reverted');
604             }
605         } else {
606             $num_reverted++;
607             my $old_record = MARC::Record->new_from_xml($rowref->{'marcxml_old'}, 'UTF-8', $rowref->{'encoding'});
608             my $biblionumber = $rowref->{'matched_biblionumber'};
609             my ($count, $oldbiblio) = GetBiblio($biblionumber);
610             $num_items_deleted += BatchRevertItems($rowref->{'import_record_id'}, $rowref->{'matched_biblionumber'});
611             ModBiblio($old_record, $biblionumber, $oldbiblio->{'frameworkcode'});
612             SetImportRecordStatus($rowref->{'import_record_id'}, 'reverted');
613         }
614     }
615     $sth->finish();
616     SetImportBatchStatus($batch_id, 'reverted');
617     return ($num_deleted, $num_errors, $num_reverted, $num_items_deleted, $num_ignored);
618 }
619
620 =head2 BatchRevertItems
621
622 =over 4
623
624 my $num_items_deleted = BatchRevertItems($import_record_id, $biblionumber);
625
626 =back
627
628 =cut
629
630 sub BatchRevertItems {
631     my ($import_record_id, $biblionumber) = @_;
632
633     my $dbh = C4::Context->dbh;
634     my $num_items_deleted = 0;
635
636     my $sth = $dbh->prepare_cached("SELECT import_items_id, itemnumber
637                                    FROM import_items
638                                    JOIN items USING (itemnumber)
639                                    WHERE import_record_id = ?");
640     $sth->bind_param(1, $import_record_id);
641     $sth->execute();
642     while (my $row = $sth->fetchrow_hashref()) {
643         DelItem($dbh, $biblionumber, $row->{'itemnumber'});
644         my $updsth = $dbh->prepare("UPDATE import_items SET status = ? WHERE import_items_id = ?");
645         $updsth->bind_param(1, 'reverted');
646         $updsth->bind_param(2, $row->{'import_items_id'});
647         $updsth->execute();
648         $updsth->finish();
649         $num_items_deleted++;
650     }
651     $sth->finish();
652     return $num_items_deleted;
653 }
654
655 =head2 GetAllImportBatches
656
657 =over 4
658
659 my $results = GetAllImportBatches();
660
661 =back
662
663 Returns a references to an array of hash references corresponding
664 to all import_batches rows (of batch_type 'batch'), sorted in 
665 ascending order by import_batch_id.
666
667 =cut
668
669 sub  GetAllImportBatches {
670     my $dbh = C4::Context->dbh;
671     my $sth = $dbh->prepare_cached("SELECT * FROM import_batches
672                                     WHERE batch_type = 'batch'
673                                     ORDER BY import_batch_id ASC");
674
675     my $results = [];
676     $sth->execute();
677     while (my $row = $sth->fetchrow_hashref) {
678         push @$results, $row;
679     }
680     $sth->finish();
681     return $results;
682 }
683
684 =head2 GetImportBatchRangeDesc
685
686 =over 4
687
688 my $results = GetImportBatchRangeDesc($offset, $results_per_group);
689
690 =back
691
692 Returns a reference to an array of hash references corresponding to
693 import_batches rows (sorted in descending order by import_batch_id)
694 start at the given offset.
695
696 =cut
697
698 sub GetImportBatchRangeDesc {
699     my ($offset, $results_per_group) = @_;
700
701     my $dbh = C4::Context->dbh;
702     my $sth = $dbh->prepare_cached("SELECT * FROM import_batches
703                                     WHERE batch_type = 'batch'
704                                     ORDER BY import_batch_id DESC
705                                     LIMIT ? OFFSET ?");
706     $sth->bind_param(1, $results_per_group);
707     $sth->bind_param(2, $offset);
708
709     my $results = [];
710     $sth->execute();
711     while (my $row = $sth->fetchrow_hashref) {
712         push @$results, $row;
713     }
714     $sth->finish();
715     return $results;
716 }
717
718 =head2 GetNumberOfImportBatches 
719
720 =over 4
721
722 my $count = GetNumberOfImportBatches();
723
724 =back
725
726 =cut
727
728 sub GetNumberOfNonZ3950ImportBatches {
729     my $dbh = C4::Context->dbh;
730     my $sth = $dbh->prepare("SELECT COUNT(*) FROM import_batches WHERE batch_type='batch'");
731     $sth->execute();
732     my ($count) = $sth->fetchrow_array();
733     $sth->finish();
734     return $count;
735 }
736
737 =head2 GetImportBibliosRange
738
739 =over 4
740
741 my $results = GetImportBibliosRange($batch_id, $offset, $results_per_group);
742
743 =back
744
745 Returns a reference to an array of hash references corresponding to
746 import_biblios/import_records rows for a given batch
747 starting at the given offset.
748
749 =cut
750
751 sub GetImportBibliosRange {
752     my ($batch_id, $offset, $results_per_group) = @_;
753
754     my $dbh = C4::Context->dbh;
755     my $sth = $dbh->prepare_cached("SELECT title, author, isbn, issn, import_record_id, record_sequence,
756                                            status, overlay_status
757                                     FROM   import_records
758                                     JOIN   import_biblios USING (import_record_id)
759                                     WHERE  import_batch_id = ?
760                                     ORDER BY import_record_id LIMIT ? OFFSET ?");
761     $sth->bind_param(1, $batch_id);
762     $sth->bind_param(2, $results_per_group);
763     $sth->bind_param(3, $offset);
764     my $results = [];
765     $sth->execute();
766     while (my $row = $sth->fetchrow_hashref) {
767         push @$results, $row;
768     }
769     $sth->finish();
770     return $results;
771
772 }
773
774 =head2 GetBestRecordMatch
775
776 =over 4
777
778 my $record_id = GetBestRecordMatch($import_record_id);
779
780 =back
781
782 =cut
783
784 sub GetBestRecordMatch {
785     my ($import_record_id) = @_;
786
787     my $dbh = C4::Context->dbh;
788     my $sth = $dbh->prepare("SELECT candidate_match_id
789                              FROM   import_record_matches
790                              WHERE  import_record_id = ?
791                              ORDER BY score DESC, candidate_match_id DESC");
792     $sth->execute($import_record_id);
793     my ($record_id) = $sth->fetchrow_array();
794     $sth->finish();
795     return $record_id;
796 }
797
798 =head2 GetImportBatchStatus
799
800 =over 4
801
802 my $status = GetImportBatchStatus($batch_id);
803
804 =back
805
806 =cut
807
808 sub GetImportBatchStatus {
809     my ($batch_id) = @_;
810
811     my $dbh = C4::Context->dbh;
812     my $sth = $dbh->prepare("SELECT import_status FROM import_batches WHERE batch_id = ?");
813     $sth->execute($batch_id);
814     my ($status) = $sth->fetchrow_array();
815     $sth->finish();
816     return;
817
818 }
819
820
821 =head2 SetImportBatchStatus
822
823 =over 4
824
825 SetImportBatchStatus($batch_id, $new_status);
826
827 =back
828
829 =cut
830
831 sub SetImportBatchStatus {
832     my ($batch_id, $new_status) = @_;
833
834     my $dbh = C4::Context->dbh;
835     my $sth = $dbh->prepare("UPDATE import_batches SET import_status = ? WHERE import_batch_id = ?");
836     $sth->execute($new_status, $batch_id);
837     $sth->finish();
838
839 }
840
841 =head2 GetImportBatchOverlayAction
842
843 =over 4
844
845 my $overlay_action = GetImportBatchOverlayAction($batch_id);
846
847 =back
848
849 =cut
850
851 sub GetImportBatchOverlayAction {
852     my ($batch_id) = @_;
853
854     my $dbh = C4::Context->dbh;
855     my $sth = $dbh->prepare("SELECT overlay_action FROM import_batches WHERE import_batch_id = ?");
856     $sth->execute($batch_id);
857     my ($overlay_action) = $sth->fetchrow_array();
858     $sth->finish();
859     return $overlay_action;
860
861 }
862
863
864 =head2 SetImportBatchOverlayAction
865
866 =over 4
867
868 SetImportBatchOverlayAction($batch_id, $new_overlay_action);
869
870 =back
871
872 =cut
873
874 sub SetImportBatchOverlayAction {
875     my ($batch_id, $new_overlay_action) = @_;
876
877     my $dbh = C4::Context->dbh;
878     my $sth = $dbh->prepare("UPDATE import_batches SET overlay_action = ? WHERE import_batch_id = ?");
879     $sth->execute($new_overlay_action, $batch_id);
880     $sth->finish();
881
882 }
883
884 =head2 GetImportBatchMatcher
885
886 =over 4
887
888 my $matcher_id = GetImportBatchMatcher($batch_id);
889
890 =back
891
892 =cut
893
894 sub GetImportBatchMatcher {
895     my ($batch_id) = @_;
896
897     my $dbh = C4::Context->dbh;
898     my $sth = $dbh->prepare("SELECT matcher_id FROM import_batches WHERE import_batch_id = ?");
899     $sth->execute($batch_id);
900     my ($matcher_id) = $sth->fetchrow_array();
901     $sth->finish();
902     return $matcher_id;
903
904 }
905
906
907 =head2 SetImportBatchMatcher
908
909 =over 4
910
911 SetImportBatchMatcher($batch_id, $new_matcher_id);
912
913 =back
914
915 =cut
916
917 sub SetImportBatchMatcher {
918     my ($batch_id, $new_matcher_id) = @_;
919
920     my $dbh = C4::Context->dbh;
921     my $sth = $dbh->prepare("UPDATE import_batches SET matcher_id = ? WHERE import_batch_id = ?");
922     $sth->execute($new_matcher_id, $batch_id);
923     $sth->finish();
924
925 }
926
927 =head2 GetImportRecordOverlayStatus
928
929 =over 4
930
931 my $overlay_status = GetImportRecordOverlayStatus($import_record_id);
932
933 =back
934
935 =cut
936
937 sub GetImportRecordOverlayStatus {
938     my ($import_record_id) = @_;
939
940     my $dbh = C4::Context->dbh;
941     my $sth = $dbh->prepare("SELECT overlay_status FROM import_records WHERE import_record_id = ?");
942     $sth->execute($import_record_id);
943     my ($overlay_status) = $sth->fetchrow_array();
944     $sth->finish();
945     return $overlay_status;
946
947 }
948
949
950 =head2 SetImportRecordOverlayStatus
951
952 =over 4
953
954 SetImportRecordOverlayStatus($import_record_id, $new_overlay_status);
955
956 =back
957
958 =cut
959
960 sub SetImportRecordOverlayStatus {
961     my ($import_record_id, $new_overlay_status) = @_;
962
963     my $dbh = C4::Context->dbh;
964     my $sth = $dbh->prepare("UPDATE import_records SET overlay_status = ? WHERE import_record_id = ?");
965     $sth->execute($new_overlay_status, $import_record_id);
966     $sth->finish();
967
968 }
969
970 =head2 GetImportRecordStatus
971
972 =over 4
973
974 my $overlay_status = GetImportRecordStatus($import_record_id);
975
976 =back
977
978 =cut
979
980 sub GetImportRecordStatus {
981     my ($import_record_id) = @_;
982
983     my $dbh = C4::Context->dbh;
984     my $sth = $dbh->prepare("SELECT status FROM import_records WHERE import_record_id = ?");
985     $sth->execute($import_record_id);
986     my ($overlay_status) = $sth->fetchrow_array();
987     $sth->finish();
988     return $overlay_status;
989
990 }
991
992
993 =head2 SetImportRecordStatus
994
995 =over 4
996
997 SetImportRecordStatus($import_record_id, $new_overlay_status);
998
999 =back
1000
1001 =cut
1002
1003 sub SetImportRecordStatus {
1004     my ($import_record_id, $new_overlay_status) = @_;
1005
1006     my $dbh = C4::Context->dbh;
1007     my $sth = $dbh->prepare("UPDATE import_records SET status = ? WHERE import_record_id = ?");
1008     $sth->execute($new_overlay_status, $import_record_id);
1009     $sth->finish();
1010
1011 }
1012
1013 =head2 GetImportRecordMatches
1014
1015 =over 4
1016
1017 my $results = GetImportRecordMatches($import_record_id, $best_only);
1018
1019 =back
1020
1021 =cut
1022
1023 sub GetImportRecordMatches {
1024     my $import_record_id = shift;
1025     my $best_only = @_ ? shift : 0;
1026
1027     my $dbh = C4::Context->dbh;
1028     # FIXME currently biblio only
1029     my $sth = $dbh->prepare_cached("SELECT title, author, biblionumber, score
1030                                     FROM import_records
1031                                     JOIN import_record_matches USING (import_record_id)
1032                                     JOIN biblio ON (biblionumber = candidate_match_id)
1033                                     WHERE import_record_id = ?
1034                                     ORDER BY score DESC, biblionumber DESC");
1035     $sth->bind_param(1, $import_record_id);
1036     my $results = [];
1037     $sth->execute();
1038     while (my $row = $sth->fetchrow_hashref) {
1039         push @$results, $row;
1040         last if $best_only;
1041     }
1042     $sth->finish();
1043
1044     return $results;
1045     
1046 }
1047
1048
1049 =head2 SetImportRecordMatches
1050
1051 =over 4
1052
1053 SetImportRecordMatches($import_record_id, @matches);
1054
1055 =back
1056
1057 =cut
1058
1059 sub SetImportRecordMatches {
1060     my $import_record_id = shift;
1061     my @matches = @_;
1062
1063     my $dbh = C4::Context->dbh;
1064     my $delsth = $dbh->prepare("DELETE FROM import_record_matches WHERE import_record_id = ?");
1065     $delsth->execute($import_record_id);
1066     $delsth->finish();
1067
1068     my $sth = $dbh->prepare("INSERT INTO import_record_matches (import_record_id, candidate_match_id, score)
1069                                     VALUES (?, ?, ?)");
1070     foreach my $match (@matches) {
1071         $sth->execute($import_record_id, $match->{'record_id'}, $match->{'score'});
1072     }
1073 }
1074
1075
1076 # internal functions
1077
1078 sub _create_import_record {
1079     my ($batch_id, $record_sequence, $marc_record, $record_type, $encoding, $z3950random) = @_;
1080
1081     my $dbh = C4::Context->dbh;
1082     my $sth = $dbh->prepare("INSERT INTO import_records (import_batch_id, record_sequence, marc, marcxml, 
1083                                                          record_type, encoding, z3950random)
1084                                     VALUES (?, ?, ?, ?, ?, ?, ?)");
1085     $sth->execute($batch_id, $record_sequence, $marc_record->as_usmarc(), $marc_record->as_xml(),
1086                   $record_type, $encoding, $z3950random);
1087     my $import_record_id = $dbh->{'mysql_insertid'};
1088     $sth->finish();
1089     return $import_record_id;
1090 }
1091
1092 sub _update_import_record_marc {
1093     my ($import_record_id, $marc_record) = @_;
1094
1095     my $dbh = C4::Context->dbh;
1096     my $sth = $dbh->prepare("UPDATE import_records SET marc = ?, marcxml = ?
1097                              WHERE  import_record_id = ?");
1098     $sth->execute($marc_record->as_usmarc(), $marc_record->as_xml(), $import_record_id);
1099     $sth->finish();
1100 }
1101
1102 sub _add_biblio_fields {
1103     my ($import_record_id, $marc_record) = @_;
1104
1105     my ($title, $author, $isbn, $issn) = _parse_biblio_fields($marc_record);
1106     my $dbh = C4::Context->dbh;
1107     # FIXME no controlnumber, originalsource
1108     # FIXME 2 - should regularize normalization of ISBN wherever it is done
1109     $isbn =~ s/\(.*$//;
1110     $isbn =~ tr/ -_//;  
1111     $isbn = uc $isbn;
1112     my $sth = $dbh->prepare("INSERT INTO import_biblios (import_record_id, title, author, isbn, issn) VALUES (?, ?, ?, ?, ?)");
1113     $sth->execute($import_record_id, $title, $author, $isbn, $issn);
1114     $sth->finish();
1115                 
1116 }
1117
1118 sub _update_biblio_fields {
1119     my ($import_record_id, $marc_record) = @_;
1120
1121     my ($title, $author, $isbn, $issn) = _parse_biblio_fields($marc_record);
1122     my $dbh = C4::Context->dbh;
1123     # FIXME no controlnumber, originalsource
1124     # FIXME 2 - should regularize normalization of ISBN wherever it is done
1125     $isbn =~ s/\(.*$//;
1126     $isbn =~ tr/ -_//;
1127     $isbn = uc $isbn;
1128     my $sth = $dbh->prepare("UPDATE import_biblios SET title = ?, author = ?, isbn = ?, issn = ?
1129                              WHERE  import_record_id = ?");
1130     $sth->execute($title, $author, $isbn, $issn, $import_record_id);
1131     $sth->finish();
1132 }
1133
1134 sub _parse_biblio_fields {
1135     my ($marc_record) = @_;
1136
1137     my $dbh = C4::Context->dbh;
1138     my $bibliofields = TransformMarcToKoha($dbh, $marc_record, '');
1139     return ($bibliofields->{'title'}, $bibliofields->{'author'}, $bibliofields->{'isbn'}, $bibliofields->{'issn'});
1140
1141 }
1142
1143 sub _update_batch_record_counts {
1144     my ($batch_id) = @_;
1145
1146     my $dbh = C4::Context->dbh;
1147     my $sth = $dbh->prepare_cached("UPDATE import_batches SET num_biblios = (
1148                                     SELECT COUNT(*)
1149                                     FROM import_records
1150                                     WHERE import_batch_id = import_batches.import_batch_id
1151                                     AND record_type = 'biblio')
1152                                     WHERE import_batch_id = ?");
1153     $sth->bind_param(1, $batch_id);
1154     $sth->execute();
1155     $sth->finish();
1156     $sth = $dbh->prepare_cached("UPDATE import_batches SET num_items = (
1157                                     SELECT COUNT(*)
1158                                     FROM import_records
1159                                     JOIN import_items USING (import_record_id)
1160                                     WHERE import_batch_id = import_batches.import_batch_id
1161                                     AND record_type = 'biblio')
1162                                     WHERE import_batch_id = ?");
1163     $sth->bind_param(1, $batch_id);
1164     $sth->execute();
1165     $sth->finish();
1166
1167 }
1168
1169 1;
1170 __END__
1171
1172 =head1 AUTHOR
1173
1174 Koha Development Team <info@koha.org>
1175
1176 Galen Charlton <galen.charlton@liblime.com>
1177
1178 =cut