]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Vandelay.pm
initial item-import-failure reporting; needs testing
[working/Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / Application / Vandelay.pm
1 package OpenILS::Application::Vandelay;
2 use strict; use warnings;
3 use OpenILS::Application;
4 use base qw/OpenILS::Application/;
5 use Unicode::Normalize;
6 use OpenSRF::EX qw/:try/;
7 use OpenSRF::AppSession;
8 use OpenSRF::Utils::SettingsClient;
9 use OpenSRF::Utils::Cache;
10 use OpenILS::Utils::Fieldmapper;
11 use OpenILS::Utils::CStoreEditor qw/:funcs/;
12 use MARC::Batch;
13 use MARC::Record;
14 use MARC::File::XML ( BinaryEncoding => 'UTF-8' );
15 use OpenILS::Utils::Fieldmapper;
16 use Time::HiRes qw(time);
17 use OpenSRF::Utils::Logger qw/$logger/;
18 use MIME::Base64;
19 use OpenILS::Const qw/:const/;
20 use OpenILS::Application::AppUtils;
21 use OpenILS::Application::Cat::BibCommon;
22 use OpenILS::Application::Cat::AuthCommon;
23 use OpenILS::Application::Cat::AssetCommon;
24 my $U = 'OpenILS::Application::AppUtils';
25
26 # A list of LDR/06 values from http://loc.gov/marc
27 my %record_types = (
28         a => 'bib',
29         c => 'bib',
30         d => 'bib',
31         e => 'bib',
32         f => 'bib',
33         g => 'bib',
34         i => 'bib',
35         j => 'bib',
36         k => 'bib',
37         m => 'bib',
38         o => 'bib',
39         p => 'bib',
40         r => 'bib',
41         t => 'bib',
42         u => 'holdings',
43         v => 'holdings',
44         x => 'holdings',
45         y => 'holdings',
46         z => 'auth',
47       ' ' => 'bib',
48 );
49
50 sub initialize {}
51 sub child_init {}
52
53 # --------------------------------------------------------------------------------
54 # Biblio ingest
55
56 sub create_bib_queue {
57     my $self = shift;
58     my $client = shift;
59     my $auth = shift;
60     my $name = shift;
61     my $owner = shift;
62     my $type = shift;
63     my $import_def = shift;
64
65     my $e = new_editor(authtoken => $auth, xact => 1);
66
67     return $e->die_event unless $e->checkauth;
68     return $e->die_event unless $e->allowed('CREATE_BIB_IMPORT_QUEUE');
69     $owner ||= $e->requestor->id;
70
71     if ($e->search_vandelay_bib_queue( {name => $name, owner => $owner, queue_type => $type})->[0]) {
72         $e->rollback;
73         return OpenILS::Event->new('BIB_QUEUE_EXISTS') 
74     }
75
76     my $queue = new Fieldmapper::vandelay::bib_queue();
77     $queue->name( $name );
78     $queue->owner( $owner );
79     $queue->queue_type( $type ) if ($type);
80     $queue->item_attr_def( $import_def ) if ($import_def);
81
82     my $new_q = $e->create_vandelay_bib_queue( $queue );
83     return $e->die_event unless ($new_q);
84     $e->commit;
85
86     return $new_q;
87 }
88 __PACKAGE__->register_method(  
89     api_name   => "open-ils.vandelay.bib_queue.create",
90     method     => "create_bib_queue",
91     api_level  => 1,
92     argc       => 4,
93 );                      
94
95
96 sub create_auth_queue {
97     my $self = shift;
98     my $client = shift;
99     my $auth = shift;
100     my $name = shift;
101     my $owner = shift;
102     my $type = shift;
103
104     my $e = new_editor(authtoken => $auth, xact => 1);
105
106     return $e->die_event unless $e->checkauth;
107     return $e->die_event unless $e->allowed('CREATE_AUTHORITY_IMPORT_QUEUE');
108     $owner ||= $e->requestor->id;
109
110     if ($e->search_vandelay_bib_queue({name => $name, owner => $owner, queue_type => $type})->[0]) {
111         $e->rollback;
112         return OpenILS::Event->new('AUTH_QUEUE_EXISTS') 
113     }
114
115     my $queue = new Fieldmapper::vandelay::authority_queue();
116     $queue->name( $name );
117     $queue->owner( $owner );
118     $queue->queue_type( $type ) if ($type);
119
120     my $new_q = $e->create_vandelay_authority_queue( $queue );
121     $e->die_event unless ($new_q);
122     $e->commit;
123
124     return $new_q;
125 }
126 __PACKAGE__->register_method(  
127     api_name   => "open-ils.vandelay.authority_queue.create",
128     method     => "create_auth_queue",
129     api_level  => 1,
130     argc       => 3,
131 );                      
132
133 sub add_record_to_bib_queue {
134     my $self = shift;
135     my $client = shift;
136     my $auth = shift;
137     my $queue = shift;
138     my $marc = shift;
139     my $purpose = shift;
140     my $bib_source = shift;
141
142     my $e = new_editor(authtoken => $auth, xact => 1);
143
144     $queue = $e->retrieve_vandelay_bib_queue($queue);
145
146     return $e->die_event unless $e->checkauth;
147     return $e->die_event unless
148         ($e->allowed('CREATE_BIB_IMPORT_QUEUE', undef, $queue) ||
149          $e->allowed('CREATE_BIB_IMPORT_QUEUE'));
150
151     my $new_rec = _add_bib_rec($e, $marc, $queue->id, $purpose, $bib_source);
152
153     return $e->die_event unless ($new_rec);
154     $e->commit;
155     return $new_rec;
156 }
157 __PACKAGE__->register_method(  
158     api_name   => "open-ils.vandelay.queued_bib_record.create",
159     method     => "add_record_to_bib_queue",
160     api_level  => 1,
161     argc       => 3,
162 );                      
163
164 sub _add_bib_rec {
165     my $e = shift;
166     my $marc = shift;
167     my $queue = shift;
168     my $purpose = shift;
169     my $bib_source = shift;
170
171     my $rec = new Fieldmapper::vandelay::queued_bib_record();
172     $rec->marc( $marc );
173     $rec->queue( $queue );
174     $rec->purpose( $purpose ) if ($purpose);
175     $rec->bib_source($bib_source);
176
177     return $e->create_vandelay_queued_bib_record( $rec );
178 }
179
180 sub add_record_to_authority_queue {
181     my $self = shift;
182     my $client = shift;
183     my $auth = shift;
184     my $queue = shift;
185     my $marc = shift;
186     my $purpose = shift;
187
188     my $e = new_editor(authtoken => $auth, xact => 1);
189
190     $queue = $e->retrieve_vandelay_authority_queue($queue);
191
192     return $e->die_event unless $e->checkauth;
193     return $e->die_event unless
194         ($e->allowed('CREATE_AUTHORITY_IMPORT_QUEUE', undef, $queue) ||
195          $e->allowed('CREATE_AUTHORITY_IMPORT_QUEUE'));
196
197     my $new_rec = _add_auth_rec($e, $marc, $queue->id, $purpose);
198
199     return $e->die_event unless ($new_rec);
200     $e->commit;
201     return $new_rec;
202 }
203 __PACKAGE__->register_method(
204     api_name   => "open-ils.vandelay.queued_authority_record.create",
205     method     => "add_record_to_authority_queue",
206     api_level  => 1,
207     argc       => 3,
208 );
209
210 sub _add_auth_rec {
211     my $e = shift;
212     my $marc = shift;
213     my $queue = shift;
214     my $purpose = shift;
215
216     my $rec = new Fieldmapper::vandelay::queued_authority_record();
217     $rec->marc( $marc );
218     $rec->queue( $queue );
219     $rec->purpose( $purpose ) if ($purpose);
220
221     return $e->create_vandelay_queued_authority_record( $rec );
222 }
223
224 sub process_spool {
225     my $self = shift;
226     my $client = shift;
227     my $auth = shift;
228     my $fingerprint = shift || '';
229     my $queue_id = shift;
230     my $purpose = shift;
231     my $filename = shift;
232     my $bib_source = shift;
233
234     my $e = new_editor(authtoken => $auth, xact => 1);
235     return $e->die_event unless $e->checkauth;
236
237     my $queue;
238     my $type = $self->{record_type};
239
240     if($type eq 'bib') {
241         $queue = $e->retrieve_vandelay_bib_queue($queue_id) or return $e->die_event;
242     } else {
243         $queue = $e->retrieve_vandelay_authority_queue($queue_id) or return $e->die_event;
244     }
245
246     my $evt = check_queue_perms($e, $type, $queue);
247     return $evt if ($evt);
248
249     my $cache = new OpenSRF::Utils::Cache();
250
251     if($fingerprint) {
252         my $data = $cache->get_cache('vandelay_import_spool_' . $fingerprint);
253         $purpose = $data->{purpose};
254         $filename = $data->{path};
255         $bib_source = $data->{bib_source};
256     }
257
258     unless(-r $filename) {
259         $logger->error("unable to read MARC file $filename");
260         return -1; # make this an event XXX
261     }
262
263     $logger->info("vandelay spooling $fingerprint purpose=$purpose file=$filename");
264
265     my $marctype = 'USMARC'; 
266
267     open F, $filename;
268     $marctype = 'XML' if (getc(F) =~ /^\D/o);
269     close F;
270
271     my $batch = new MARC::Batch ($marctype, $filename);
272     $batch->strict_off;
273
274     my $response_scale = 10;
275     my $count = 0;
276     my $r = -1;
277     while (try { $r = $batch->next } otherwise { $r = -1 }) {
278         if ($r == -1) {
279             $logger->warn("Processing of record $count in set $filename failed.  Skipping this record");
280             $count++;
281         }
282
283         $logger->info("processing record $count");
284
285         try {
286             (my $xml = $r->as_xml_record()) =~ s/\n//sog;
287             $xml =~ s/^<\?xml.+\?\s*>//go;
288             $xml =~ s/>\s+</></go;
289             $xml =~ s/\p{Cc}//go;
290             $xml = $U->entityize($xml);
291             $xml =~ s/[\x00-\x1f]//go;
292
293             my $qrec;
294             # Check the leader to ensure we've got something resembling the expected
295             # Allow spaces to give records the benefit of the doubt
296             my $ldr_type = substr($r->leader(), 6, 1);
297             if ($type eq 'bib' && ($record_types{$ldr_type}) eq 'bib' || $ldr_type eq ' ') {
298                 $qrec = _add_bib_rec( $e, $xml, $queue_id, $purpose, $bib_source ) or return $e->die_event;
299             } elsif ($type eq 'auth' && ($record_types{$ldr_type}) eq 'auth' || $ldr_type eq ' ') {
300                 $qrec = _add_auth_rec( $e, $xml, $queue_id, $purpose ) or return $e->die_event;
301             } else {
302                 # I don't know how to handle this type; rock on
303                 $logger->error("In process_spool(), type was $type and leader type was $ldr_type ; not currently supported");
304                 next;
305             }
306
307             if($self->api_name =~ /stream_results/ and $qrec) {
308                 $client->respond($qrec->id)
309             } else {
310                 $client->respond($count) if (++$count % $response_scale) == 0;
311                 $response_scale *= 10 if ($count == ($response_scale * 10));
312             }
313         } catch Error with {
314             my $error = shift;
315             $logger->warn("Encountered a bad record at Vandelay ingest: ".$error);
316         }
317     }
318
319     $e->commit;
320     unlink($filename);
321     $cache->delete_cache('vandelay_import_spool_' . $fingerprint) if $fingerprint;
322     return $count;
323 }
324
325 __PACKAGE__->register_method(  
326     api_name    => "open-ils.vandelay.bib.process_spool",
327     method      => "process_spool",
328     api_level   => 1,
329     argc        => 3,
330     max_chunk_size => 0,
331     record_type => 'bib'
332 );                      
333 __PACKAGE__->register_method(  
334     api_name    => "open-ils.vandelay.auth.process_spool",
335     method      => "process_spool",
336     api_level   => 1,
337     argc        => 3,
338     max_chunk_size => 0,
339     record_type => 'auth'
340 );                      
341
342 __PACKAGE__->register_method(  
343     api_name    => "open-ils.vandelay.bib.process_spool.stream_results",
344     method      => "process_spool",
345     api_level   => 1,
346     argc        => 3,
347     stream      => 1,
348     max_chunk_size => 0,
349     record_type => 'bib'
350 );                      
351 __PACKAGE__->register_method(  
352     api_name    => "open-ils.vandelay.auth.process_spool.stream_results",
353     method      => "process_spool",
354     api_level   => 1,
355     argc        => 3,
356     stream      => 1,
357     max_chunk_size => 0,
358     record_type => 'auth'
359 );
360
361 __PACKAGE__->register_method(  
362     api_name    => "open-ils.vandelay.bib_queue.records.retrieve",
363     method      => 'retrieve_queued_records',
364     api_level   => 1,
365     argc        => 2,
366     stream      => 1,
367     record_type => 'bib'
368 );
369 __PACKAGE__->register_method(  
370     api_name    => "open-ils.vandelay.auth_queue.records.retrieve",
371     method      => 'retrieve_queued_records',
372     api_level   => 1,
373     argc        => 2,
374     stream      => 1,
375     record_type => 'auth'
376 );
377
378 __PACKAGE__->register_method(  
379     api_name    => "open-ils.vandelay.bib_queue.records.matches.retrieve",
380     method      => 'retrieve_queued_records',
381     api_level   => 1,
382     argc        => 2,
383     stream      => 1,
384     record_type => 'bib',
385     signature   => {
386         desc => q/Only retrieve queued bib records that have matches against existing records/
387     }
388 );
389 __PACKAGE__->register_method(  
390     api_name    => "open-ils.vandelay.auth_queue.records.matches.retrieve",
391     method      => 'retrieve_queued_records',
392     api_level   => 1,
393     argc        => 2,
394     stream      => 1,
395     record_type => 'auth',
396     signature   => {
397         desc => q/Only retrieve queued authority records that have matches against existing records/
398     }
399
400 );
401
402 sub retrieve_queued_records {
403     my($self, $conn, $auth, $queue_id, $options) = @_;
404     my $e = new_editor(authtoken => $auth, xact => 1);
405     return $e->die_event unless $e->checkauth;
406     $options ||= {};
407     my $limit = $$options{limit} || 20;
408     my $offset = $$options{offset} || 0;
409
410     my $type = $self->{record_type};
411     my $queue;
412     if($type eq 'bib') {
413         $queue = $e->retrieve_vandelay_bib_queue($queue_id) or return $e->die_event;
414     } else {
415         $queue = $e->retrieve_vandelay_authority_queue($queue_id) or return $e->die_event;
416     }
417     my $evt = check_queue_perms($e, $type, $queue);
418     return $evt if ($evt);
419
420     my $class = ($type eq 'bib') ? 'vqbr' : 'vqar';
421     my $search = ($type eq 'bib') ? 
422         'search_vandelay_queued_bib_record' : 'search_vandelay_queued_authority_record';
423     my $retrieve = ($type eq 'bib') ? 
424         'retrieve_vandelay_queued_bib_record' : 'retrieve_vandelay_queued_authority_record';
425
426     my $filter = ($$options{non_imported}) ? {import_time => undef} : {};
427
428     my $record_ids;
429     if($self->api_name =~ /matches/) {
430         # fetch only matched records
431         $record_ids = queued_records_with_matches($e, $type, $queue_id, $limit, $offset, $filter);
432     } else {
433         # fetch all queue records
434         $record_ids = $e->$search([
435                 {queue => $queue_id, %$filter}, 
436                 {order_by => {$class => 'id'}, limit => $limit, offset => $offset}
437             ],
438             {idlist => 1}
439         );
440     }
441
442
443     for my $rec_id (@$record_ids) {
444         my $params = {   
445             flesh => 1,
446             flesh_fields => {$class => ['attributes', 'matches']},
447         };
448         my $rec = $e->$retrieve([$rec_id, $params]);
449         $rec->clear_marc if $$options{clear_marc};
450         $conn->respond($rec);
451     }
452     $e->rollback;
453     return undef;
454 }
455
456 sub check_queue_perms {
457     my($e, $type, $queue) = @_;
458     if ($type eq 'bib') {
459         return $e->die_event unless
460             ($e->allowed('CREATE_BIB_IMPORT_QUEUE', undef, $queue) ||
461              $e->allowed('CREATE_BIB_IMPORT_QUEUE'));
462     } else {
463         return $e->die_event unless
464             ($e->allowed('CREATE_AUTHORITY_IMPORT_QUEUE', undef, $queue) ||
465              $e->allowed('CREATE_AUTHORITY_IMPORT_QUEUE'));
466     }
467
468     return undef;
469 }
470
471 __PACKAGE__->register_method(  
472     api_name    => "open-ils.vandelay.bib_record.list.import",
473     method      => 'import_record_list',
474     api_level   => 1,
475     argc        => 2,
476     stream      => 1,
477     record_type => 'bib'
478 );
479
480 __PACKAGE__->register_method(  
481     api_name    => "open-ils.vandelay.auth_record.list.import",
482     method      => 'import_record_list',
483     api_level   => 1,
484     argc        => 2,
485     stream      => 1,
486     record_type => 'auth'
487 );
488
489 sub import_record_list {
490     my($self, $conn, $auth, $rec_ids, $args) = @_;
491     my $e = new_editor(authtoken => $auth, xact => 1);
492     return $e->die_event unless $e->checkauth;
493     $args ||= {};
494     my $err = import_record_list_impl($self, $conn, $rec_ids, $e->requestor, $args);
495     $e->rollback;
496     return $err if $err;
497     return {complete => 1};
498 }
499
500
501 __PACKAGE__->register_method(  
502     api_name    => "open-ils.vandelay.bib_queue.import",
503     method      => 'import_queue',
504     api_level   => 1,
505     argc        => 2,
506     stream      => 1,
507     max_chunk_size => 0,
508     record_type => 'bib'
509 );
510
511 __PACKAGE__->register_method(  
512     api_name    => "open-ils.vandelay.auth_queue.import",
513     method      => 'import_queue',
514     api_level   => 1,
515     argc        => 2,
516     stream      => 1,
517     max_chunk_size => 0,
518     record_type => 'auth'
519 );
520 __PACKAGE__->register_method(  
521     api_name    => "open-ils.vandelay.bib_queue.nomatch.import",
522     method      => 'import_queue',
523     api_level   => 1,
524     argc        => 2,
525     stream      => 1,
526     signature   => {
527         desc => q/Only import records that have no collisions/
528     },
529     max_chunk_size => 0,
530     record_type => 'bib'
531 );
532
533 __PACKAGE__->register_method(  
534     api_name    => "open-ils.vandelay.auth_queue.nomatch.import",
535     method      => 'import_queue',
536     api_level   => 1,
537     argc        => 2,
538     stream      => 1,
539     signature   => {
540         desc => q/Only import records that have no collisions/
541     },
542     max_chunk_size => 0,
543     record_type => 'auth'
544 );
545 sub import_queue {
546     my($self, $conn, $auth, $q_id, $options) = @_;
547     my $e = new_editor(authtoken => $auth, xact => 1);
548     return $e->die_event unless $e->checkauth;
549     $options ||= {};
550     my $type = $self->{record_type};
551     my $class = ($type eq 'bib') ? 'vqbr' : 'vqar';
552
553     my $query = {queue => $q_id, import_time => undef};
554
555     if($self->api_name =~ /nomatch/) {
556         my $matched_recs = queued_records_with_matches($e, $type, $q_id, undef, undef, {import_time => undef});
557         $query->{id} = {'not in' => $matched_recs} if @$matched_recs;
558     }
559
560     my $search = ($type eq 'bib') ? 
561         'search_vandelay_queued_bib_record' : 'search_vandelay_queued_authority_record';
562     my $rec_ids = $e->$search($query, {idlist => 1});
563     my $err = import_record_list_impl($self, $conn, $rec_ids, $e->requestor, $options);
564     try {$e->rollback} otherwise {}; # only using this to make the read authoritative -- don't die from it
565     return $err if $err;
566     return {complete => 1};
567 }
568
569 # returns a list of queued record IDs for a given queue that 
570 # have at least one entry in the match table
571 sub queued_records_with_matches {
572     my($e, $type, $q_id, $limit, $offset, $filter) = @_;
573
574     my $match_class = 'vbm';
575     my $rec_class = 'vqbr';
576     if($type eq 'auth') {
577         $match_class = 'vam';
578          $rec_class = 'vqar';
579     }
580
581     $filter ||= {};
582     $filter->{queue} = $q_id;
583
584     my $query = {
585         distinct => 1, 
586         select => {$match_class => ['queued_record']}, 
587         from => {
588             $match_class => {
589                 $rec_class => {
590                     field => 'id',
591                     fkey => 'queued_record',
592                     filter => $filter,
593                 }
594             }
595         }
596     };        
597
598     if($limit or defined $offset) {
599         $limit ||= 20;
600         $offset ||= 0;
601         $query->{limit} = $limit;
602         $query->{offset} = $offset;
603     }
604
605     my $data = $e->json_query($query);
606     return [ map {$_->{queued_record}} @$data ];
607 }
608
609 sub import_record_list_impl {
610     my($self, $conn, $rec_ids, $requestor, $args) = @_;
611
612     my $overlay_map = $args->{overlay_map} || {};
613     my $type = $self->{record_type};
614     my $total = @$rec_ids;
615     my $count = 0;
616     my %queues;
617
618     my $step = 1;
619
620     my $auto_overlay_exact = $$args{auto_overlay_exact};
621     my $auto_overlay_1match = $$args{auto_overlay_1match};
622     my $merge_profile = $$args{merge_profile};
623     my $bib_source = $$args{bib_source};
624     my $report_all = $$args{report_all};
625
626     my $overlay_func = 'vandelay.overlay_bib_record';
627     my $auto_overlay_func = 'vandelay.auto_overlay_bib_record';
628     my $retrieve_func = 'retrieve_vandelay_queued_bib_record';
629     my $update_func = 'update_vandelay_queued_bib_record';
630     my $search_func = 'search_vandelay_queued_bib_record';
631     my $retrieve_queue_func = 'retrieve_vandelay_bib_queue';
632     my $update_queue_func = 'update_vandelay_bib_queue';
633     my $rec_class = 'vqbr';
634
635     my %bib_sources;
636     my $editor = new_editor();
637     my $sources = $editor->search_config_bib_source({id => {'!=' => undef}});
638
639     foreach my $src (@$sources) {
640         $bib_sources{$src->id} = $src->source;
641     }
642
643     if($type eq 'auth') {
644         $overlay_func =~ s/bib/auth/o;
645         $auto_overlay_func = s/bib/auth/o;
646         $retrieve_func =~ s/bib/authority/o;
647         $retrieve_queue_func =~ s/bib/authority/o;
648         $update_queue_func =~ s/bib/authority/o;
649         $update_func =~ s/bib/authority/o;
650         $search_func =~ s/bib/authority/o;
651         $rec_class = 'vqar';
652     }
653
654     my @success_rec_ids;
655     for my $rec_id (@$rec_ids) {
656
657         my $overlay_target = $overlay_map->{$rec_id};
658
659         my $error = 0;
660         my $e = new_editor(xact => 1);
661         $e->requestor($requestor);
662
663         my $rec = $e->$retrieve_func([
664             $rec_id,
665             {   flesh => 1,
666                 flesh_fields => { $rec_class => ['matches']},
667             }
668         ]);
669
670         unless($rec) {
671             $conn->respond({total => $total, progress => ++$count, imported => $rec_id, err_event => $e->event});
672             $e->rollback;
673             next;
674         }
675
676         if($rec->import_time) {
677             $e->rollback;
678             next;
679         }
680
681         $queues{$rec->queue} = 1;
682
683         my $record;
684         my $imported = 0;
685
686         if(defined $overlay_target) {
687             # Caller chose an explicit overlay target
688
689             my $res = $e->json_query(
690                 {
691                     from => [
692                         $overlay_func,
693                         $rec->id, 
694                         $overlay_target, 
695                         $merge_profile
696                     ]
697                 }
698             );
699
700             if($res and ($res = $res->[0])) {
701
702                 if($res->{$overlay_func} eq 't') {
703                     $logger->info("vl: $type direct overlay succeeded for queued rec " . 
704                         $rec->id . " and overlay target $overlay_target");
705                     $imported = 1;
706                 }
707
708             } else {
709                 $error = 1;
710                 $logger->error("vl: Error attempting overlay with func=$overlay_func, profile=$merge_profile, record=$rec_id");
711             }
712
713         } else {
714
715             if($auto_overlay_1match) { 
716                 # caller says to overlay if there is exactly 1 match
717
718                 my %match_recs = map { $_->eg_record => 1 } @{$rec->matches};
719
720                 if( scalar(keys %match_recs) == 1) { # all matches point to the same record
721
722                     my $res = $e->json_query(
723                         {
724                             from => [
725                                 $overlay_func,
726                                 $rec->id, 
727                                 $rec->matches->[0]->eg_record,
728                                 $merge_profile
729                             ]
730                         }
731                     );
732
733                     if($res and ($res = $res->[0])) {
734     
735                         if($res->{$overlay_func} eq 't') {
736                             $logger->info("vl: $type overlay-1match succeeded for queued rec " . $rec->id);
737                             $imported = 1;
738                         }
739
740                     } else {
741                         $error = 1;
742                         $logger->error("vl: Error attempting overlay with func=$overlay_func, profile=$merge_profile, record=$rec_id");
743                     }
744                 }
745             }
746
747             if(!$imported and !$error and $auto_overlay_exact and scalar(@{$rec->matches}) == 1 ) {
748                 
749                 # caller says to overlay if there is an /exact/ match
750
751                 my $res = $e->json_query(
752                     {
753                         from => [
754                             $auto_overlay_func,
755                             $rec->id, 
756                             $merge_profile
757                         ]
758                     }
759                 );
760
761                 if($res and ($res = $res->[0])) {
762
763                     if($res->{$auto_overlay_func} eq 't') {
764                         $logger->info("vl: $type auto-overlay succeeded for queued rec " . $rec->id);
765                         $imported = 1;
766                     }
767
768                 } else {
769                     $error = 1;
770                     $logger->error("vl: Error attempting overlay with func=$auto_overlay_func, profile=$merge_profile, record=$rec_id");
771                 }
772             }
773
774             if(!$imported and !$error) {
775             
776                 # No overlay / merge occurred.  Do a traditional record import by creating a new record
777             
778                 $logger->info("vl: creating new $type record for queued record $rec_id");
779                 if($type eq 'bib') {
780                     $record = OpenILS::Application::Cat::BibCommon->biblio_record_xml_import($e, $rec->marc, $bib_sources{$rec->bib_source});
781                 } else {
782
783                     $record = OpenILS::Application::Cat::AuthCommon->import_authority_record($e, $rec->marc); #$source);
784                 }
785
786                 if($U->event_code($record)) {
787
788                     $e->event($record); 
789                     $e->rollback;
790
791                 } else {
792
793                     $logger->info("vl: successfully imported new $type record");
794                     $rec->imported_as($record->id);
795                     $rec->import_time('now');
796
797                     $imported = 1 if $e->$update_func($rec);
798                 }
799             }
800         }
801
802         if($imported) {
803             push @success_rec_ids, $rec_id;
804             $e->commit;
805         } else {
806             # Send an update whenever there's an error
807             $conn->respond({total => $total, progress => ++$count, imported => $rec_id, err_event => $e->event});
808         }
809
810         if($report_all or (++$count % $step) == 0) {
811             $conn->respond({total => $total, progress => $count, imported => $rec_id});
812             # report often at first, climb quickly, then hold steady
813             $step *= 2 unless $step == 256;
814         }
815     }
816
817     # see if we need to mark any queues as complete
818     for my $q_id (keys %queues) {
819
820         my $e = new_editor(xact => 1);
821         my $remaining = $e->$search_func(
822             [{queue => $q_id, import_time => undef}, {limit =>1}], {idlist => 1});
823
824         unless(@$remaining) {
825             my $queue = $e->$retrieve_queue_func($q_id);
826
827             unless($U->is_true($queue->complete)) {
828                 $queue->complete('t');
829                 $e->$update_queue_func($queue) or return $e->die_event;
830                 $e->commit;
831                 next;
832             }
833         } 
834         $e->rollback;
835     }
836
837     import_record_asset_list_impl($conn, \@success_rec_ids, $requestor);
838
839     $conn->respond({total => $total, progress => $count});
840     return undef;
841 }
842
843
844 __PACKAGE__->register_method(  
845     api_name    => "open-ils.vandelay.bib_queue.owner.retrieve",
846     method      => 'owner_queue_retrieve',
847     api_level   => 1,
848     argc        => 2,
849     stream      => 1,
850     record_type => 'bib'
851 );
852 __PACKAGE__->register_method(  
853     api_name    => "open-ils.vandelay.authority_queue.owner.retrieve",
854     method      => 'owner_queue_retrieve',
855     api_level   => 1,
856     argc        => 2,
857     stream      => 1,
858     record_type => 'auth'
859 );
860
861 sub owner_queue_retrieve {
862     my($self, $conn, $auth, $owner_id, $filters) = @_;
863     my $e = new_editor(authtoken => $auth, xact => 1);
864     return $e->die_event unless $e->checkauth;
865     $owner_id = $e->requestor->id; # XXX add support for viewing other's queues?
866     my $queues;
867     $filters ||= {};
868     my $search = {owner => $owner_id};
869     $search->{$_} = $filters->{$_} for keys %$filters;
870
871     if($self->{record_type} eq 'bib') {
872         $queues = $e->search_vandelay_bib_queue(
873             [$search, {order_by => {vbq => 'evergreen.lowercase(name)'}}]);
874     } else {
875         $queues = $e->search_vandelay_authority_queue(
876             [$search, {order_by => {vaq => 'evergreen.lowercase(name)'}}]);
877     }
878     $conn->respond($_) for @$queues;
879     $e->rollback;
880     return undef;
881 }
882
883 __PACKAGE__->register_method(  
884     api_name    => "open-ils.vandelay.bib_queue.delete",
885     method      => "delete_queue",
886     api_level   => 1,
887     argc        => 2,
888     record_type => 'bib'
889 );            
890 __PACKAGE__->register_method(  
891     api_name    => "open-ils.vandelay.auth_queue.delete",
892     method      => "delete_queue",
893     api_level   => 1,
894     argc        => 2,
895     record_type => 'auth'
896 );  
897
898 sub delete_queue {
899     my($self, $conn, $auth, $q_id) = @_;
900     my $e = new_editor(xact => 1, authtoken => $auth);
901     return $e->die_event unless $e->checkauth;
902     if($self->{record_type} eq 'bib') {
903         return $e->die_event unless $e->allowed('CREATE_BIB_IMPORT_QUEUE');
904         my $queue = $e->retrieve_vandelay_bib_queue($q_id)
905             or return $e->die_event;
906         $e->delete_vandelay_bib_queue($queue)
907             or return $e->die_event;
908     } else {
909            return $e->die_event unless $e->allowed('CREATE_AUTHORITY_IMPORT_QUEUE');
910         my $queue = $e->retrieve_vandelay_authority_queue($q_id)
911             or return $e->die_event;
912         $e->delete_vandelay_authority_queue($queue)
913             or return $e->die_event;
914     }
915     $e->commit;
916     return 1;
917 }
918
919
920 __PACKAGE__->register_method(  
921     api_name    => "open-ils.vandelay.queued_bib_record.html",
922     method      => 'queued_record_html',
923     api_level   => 1,
924     argc        => 2,
925     stream      => 1,
926     record_type => 'bib'
927 );
928 __PACKAGE__->register_method(  
929     api_name    => "open-ils.vandelay.queued_authority_record.html",
930     method      => 'queued_record_html',
931     api_level   => 1,
932     argc        => 2,
933     stream      => 1,
934     record_type => 'auth'
935 );
936
937 sub queued_record_html {
938     my($self, $conn, $auth, $rec_id) = @_;
939     my $e = new_editor(xact=>1,authtoken => $auth);
940     return $e->die_event unless $e->checkauth;
941     my $rec;
942     if($self->{record_type} eq 'bib') {
943         $rec = $e->retrieve_vandelay_queued_bib_record($rec_id)
944             or return $e->die_event;
945     } else {
946         $rec = $e->retrieve_vandelay_queued_authority_record($rec_id)
947             or return $e->die_event;
948     }
949
950     $e->rollback;
951     return $U->simplereq(
952         'open-ils.search',
953         'open-ils.search.biblio.record.html', undef, 1, $rec->marc);
954 }
955
956
957 __PACKAGE__->register_method(  
958     api_name    => "open-ils.vandelay.bib_queue.summary.retrieve", 
959     method      => 'retrieve_queue_summary',
960     api_level   => 1,
961     argc        => 2,
962     stream      => 1,
963     record_type => 'bib'
964 );
965 __PACKAGE__->register_method(  
966     api_name    => "open-ils.vandelay.auth_queue.summary.retrieve",
967     method      => 'retrieve_queue_summary',
968     api_level   => 1,
969     argc        => 2,
970     stream      => 1,
971     record_type => 'auth'
972 );
973
974 sub retrieve_queue_summary {
975     my($self, $conn, $auth, $queue_id) = @_;
976     my $e = new_editor(xact=>1, authtoken => $auth);
977     return $e->die_event unless $e->checkauth;
978
979     my $queue;
980     my $type = $self->{record_type};
981     if($type eq 'bib') {
982         $queue = $e->retrieve_vandelay_bib_queue($queue_id)
983             or return $e->die_event;
984     } else {
985         $queue = $e->retrieve_vandelay_authority_queue($queue_id)
986             or return $e->die_event;
987     }
988
989     my $evt = check_queue_perms($e, $type, $queue);
990     return $evt if $evt;
991
992     my $search = 'search_vandelay_queued_bib_record';
993     $search =~ s/bib/authority/ if $type ne 'bib';
994
995     return {
996         queue => $queue,
997         total => scalar(@{$e->$search({queue => $queue_id}, {idlist=>1})}),
998         imported => scalar(@{$e->$search({queue => $queue_id, import_time => {'!=' => undef}}, {idlist=>1})}),
999     };
1000 }
1001
1002 # --------------------------------------------------------------------------------
1003 # Given a list of queued record IDs, imports all items attached to those records
1004 # --------------------------------------------------------------------------------
1005 sub import_record_asset_list_impl {
1006     my($conn, $rec_ids, $requestor) = @_;
1007
1008     my $roe = new_editor(xact=> 1, requestor => $requestor);
1009
1010     my %report_args = (
1011         conn => $conn,
1012         total => scalar(@$rec_ids),
1013         step => 1, # how often to respond
1014         progress => 0,
1015         in_count => 0,
1016     );
1017
1018     for my $rec_id (@$rec_ids) {
1019         my $rec = $roe->retrieve_vandelay_queued_bib_record($rec_id);
1020         next unless $rec and $rec->import_time;
1021         my $item_ids = $roe->search_vandelay_import_item({record => $rec->id}, {idlist=>1});
1022
1023         for my $item_id (@$item_ids) {
1024             my $e = new_editor(requestor => $requestor, xact => 1);
1025             my $item = $e->retrieve_vandelay_import_item($item_id);
1026             $report_args{progress}++;
1027             $report_args{import_item} = $item;
1028
1029             # --------------------------------------------------------------------------------
1030             # Find or create the volume
1031             # --------------------------------------------------------------------------------
1032             my ($vol, $evt) =
1033                 OpenILS::Application::Cat::AssetCommon->find_or_create_volume(
1034                     $e, $item->call_number, $rec->imported_as, $item->owning_lib);
1035
1036             if($evt) {
1037                 respond_with_status(%report_args, evt => $evt);
1038                 next;
1039             }
1040
1041             # --------------------------------------------------------------------------------
1042             # Create the new copy
1043             # --------------------------------------------------------------------------------
1044             my $copy = Fieldmapper::asset::copy->new;
1045             $copy->loan_duration(2);
1046             $copy->fine_level(2);
1047             $copy->barcode($item->barcode);
1048             $copy->location($item->location);
1049             $copy->circ_lib($item->circ_lib || $item->owning_lib);
1050             $copy->status( defined($item->status) ? $item->status : OILS_COPY_STATUS_IN_PROCESS );
1051             $copy->circulate($item->circulate);
1052             $copy->deposit($item->deposit);
1053             $copy->deposit_amount($item->deposit_amount);
1054             $copy->ref($item->ref);
1055             $copy->holdable($item->holdable);
1056             $copy->price($item->price);
1057             $copy->circ_as_type($item->circ_as_type);
1058             $copy->alert_message($item->alert_message);
1059             $copy->opac_visible($item->opac_visible);
1060             $copy->circ_modifier($item->circ_modifier);
1061
1062             # --------------------------------------------------------------------------------
1063             # see if a valid circ_modifier was provided
1064             # --------------------------------------------------------------------------------
1065             #if($copy->circ_modifier and not $e->retrieve_config_circ_modifier($item->circ_modifier)) {
1066             if($copy->circ_modifier and not $e->search_config_circ_modifier({code=>$item->circ_modifier})->[0]) {
1067                 respond_with_status(%report_args, evt => $e->die_event);
1068                 next;
1069             }
1070
1071             if($evt = OpenILS::Application::Cat::AssetCommon->create_copy($e, $vol, $copy)) {
1072                 try { $e->rollback } otherwise {}; # sometimes calls die_event, sometimes not
1073                 $report_args{evt} = $evt;
1074                 respond_with_status(%report_args);
1075                 next;
1076             }
1077
1078             # --------------------------------------------------------------------------------
1079             # create copy notes
1080             # --------------------------------------------------------------------------------
1081             $evt = OpenILS::Application::Cat::AssetCommon->create_copy_note(
1082                 $e, $copy, '', $item->pub_note, 1) if $item->pub_note;
1083
1084             if($evt) {
1085                 respond_with_status(%report_args, evt => $evt);
1086                 next;
1087             }
1088
1089             $evt = OpenILS::Application::Cat::AssetCommon->create_copy_note(
1090                 $e, $copy, '', $item->priv_note, 1) if $item->priv_note;
1091
1092             if($evt) {
1093                 respond_with_status(%report_args, evt => $evt);
1094                 next;
1095             }
1096
1097             # --------------------------------------------------------------------------------
1098             # Item import succeeded
1099             # --------------------------------------------------------------------------------
1100             $e->commit;
1101             $report_args{in_count}++;
1102             respond_with_status(%report_args, imported_as => $copy->id)
1103         }
1104     }
1105     $roe->rollback;
1106     return undef;
1107 }
1108
1109
1110 sub respond_with_status {
1111     my %args = @_;
1112
1113     #  If the import failed, track the failure reason
1114
1115     my $error = $args{import_error};
1116     my $evt = $args{evt};
1117
1118     if($error || $evt) {
1119
1120         my $item = $args{import_item};
1121
1122         my $error ||= 'general.unknown';
1123         $item->import_error($error);
1124
1125         if($evt) {
1126             my $detail = sprintf("%s : %s", $evt->{textcode}, substr($evt->{desc}, 0, 120));
1127             $item->error_detail($detail);
1128         }
1129
1130         my $e = new_editor(xact => 1);
1131         $e->update_vandelay_import_item($item);
1132         $e->commit;
1133     }
1134
1135     return unless $args{report_all} or ($args{progress} % $args{step}) == 0;
1136     $args{step} *= 2 unless $args{step} == 256;
1137
1138     $args{conn}->respond({
1139         map { $_ => $args{$_} } qw/total progress success_count/
1140     });
1141 }
1142
1143 __PACKAGE__->register_method(  
1144     api_name    => "open-ils.vandelay.match_set.get_tree",
1145     method      => "match_set_get_tree",
1146     api_level   => 1,
1147     argc        => 2,
1148     signature   => {
1149         desc    => q/For a given vms object, return a tree of match set points
1150                     represented by a vmsp object with recursively fleshed
1151                     children./
1152     }
1153 );
1154
1155 sub match_set_get_tree {
1156     my ($self, $conn, $authtoken, $match_set_id) = @_;
1157
1158     $match_set_id = int($match_set_id) or return;
1159
1160     my $e = new_editor("authtoken" => $authtoken);
1161     $e->checkauth or return $e->die_event;
1162
1163     my $set = $e->retrieve_vandelay_match_set($match_set_id) or
1164         return $e->die_event;
1165
1166     $e->allowed("ADMIN_IMPORT_MATCH_SET", $set->owner) or
1167         return $e->die_event;
1168
1169     my $tree = $e->search_vandelay_match_set_point([
1170         {"match_set" => $match_set_id, "parent" => undef},
1171         {"flesh" => -1, "flesh_fields" => {"vmsp" => ["children"]}}
1172     ]) or return $e->die_event;
1173
1174     return pop @$tree;
1175 }
1176
1177
1178 __PACKAGE__->register_method(
1179     api_name    => "open-ils.vandelay.match_set.update",
1180     method      => "match_set_update_tree",
1181     api_level   => 1,
1182     argc        => 3,
1183     signature   => {
1184         desc => q/Replace any vmsp objects associated with a given (by ID) vms
1185                 with the given objects (recursively fleshed vmsp tree)./
1186     }
1187 );
1188
1189 sub _walk_new_vmsp {
1190     my ($e, $match_set_id, $node, $parent_id) = @_;
1191
1192     my $point = new Fieldmapper::vandelay::match_set_point;
1193     $point->parent($parent_id);
1194     $point->match_set($match_set_id);
1195     $point->$_($node->$_) for (qw/bool_op svf tag subfield negate quality/);
1196
1197     $e->create_vandelay_match_set_point($point) or return $e->die_event;
1198
1199     $parent_id = $e->data->id;
1200     if ($node->children && @{$node->children}) {
1201         for (@{$node->children}) {
1202             return $e->die_event if
1203                 _walk_new_vmsp($e, $match_set_id, $_, $parent_id);
1204         }
1205     }
1206
1207     return;
1208 }
1209
1210 sub match_set_update_tree {
1211     my ($self, $conn, $authtoken, $match_set_id, $tree) = @_;
1212
1213     my $e = new_editor("xact" => 1, "authtoken" => $authtoken);
1214     $e->checkauth or return $e->die_event;
1215
1216     my $set = $e->retrieve_vandelay_match_set($match_set_id) or
1217         return $e->die_event;
1218
1219     $e->allowed("ADMIN_IMPORT_MATCH_SET", $set->owner) or
1220         return $e->die_event;
1221
1222     my $existing = $e->search_vandelay_match_set_point([
1223         {"match_set" => $match_set_id},
1224         {"order_by" => {"vmsp" => "id DESC"}}
1225     ]) or return $e->die_event;
1226
1227     foreach (@$existing) {
1228         $e->delete_vandelay_match_set_point($_) or return $e->die_event;
1229     }
1230
1231     _walk_new_vmsp($e, $match_set_id, $tree);
1232
1233     $e->commit or return $e->die_event;
1234 }
1235
1236 1;